1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
public class StringLengthValidator : BaseValidator
{
// Taille min à contrôler
[Browsable(true), Category("Validation"), DefaultValue(0), Description("Taille min du champ. 0 = pas de limite")]
public Int32 MinSize
{
get
{
Int32 minSize = 0;
if(ViewState["MinSize"] != null)
minSize = (Int32)ViewState["MinSize"];
return minSize;
}
set { ViewState["MinSize"] = value; }
}
// Taille max à contrôler
[Browsable(true), Category("Validation"), DefaultValue(0), Description("Taille max du champ. 0 = pas de limite")]
public Int32 MaxSize
{
get
{
Int32 maxSize = 0;
if(ViewState["MaxSize"] != null)
maxSize = (Int32)ViewState["MaxSize"];
return maxSize;
}
set { ViewState["MaxSize"] = value; }
}
// Fonction de test de validité
protected override bool EvaluateIsValid()
{
Int32 sizeToCompare = GetControlValidationValue(ControlToValidate).Length;
return sizeToCompare >= MinSize &&
(sizeToCompare <= MaxSize || MaxSize == 0);
}
// Ajout des valeurs pour y avoir accès en Javascript
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
if (RenderUplevel)
{
// MinSize
Page.ClientScript.RegisterExpandoAttribute(ClientID, "minlength", MinSize.ToString(), true);
// MaxSize
Page.ClientScript.RegisterExpandoAttribute(ClientID, "maxlength", MaxSize.ToString(), true);
// Fonction javascript à appeller pour validation client
Page.ClientScript.RegisterExpandoAttribute(ClientID, "evaluationfunction", "StringLengthValidatorEvaluateIsValid", false);
}
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (RenderUplevel)
{
// On enregistre la fonction javascript
Page.ClientScript.RegisterClientScriptInclude("StringLengthValidatorJavaScript",
Page.ClientScript.GetWebResourceUrl(GetType(), "Validators.StringLengthValidator.js"));
string controlid = FindControl(ControlToValidate) == null ? string.Empty : FindControl(ControlToValidate).ClientID;
// je ne sais pas ce que ça fait, j'ai juste recopié bêtement,
Page.ClientScript.RegisterStartupScript(GetType(), "hookup1", string.Format("ValidatorHookupControlID('{0}', document.all ? document.all['{1}'] : document.getElementById('{1}'));", controlid , ClientID), true);
}
}
} |
Partager