Saturday, 10 December 2016

ASP.NET 16 : Custom Validator

Validation - CustomValidator

If none of the other validators can help you, the CustomValidator usually can. It doesn't come with a predefined way of working; you write the code for validating your self. This is of course very powerful, since the possibilities are basically endless. A common way of using the CustomValidator is when you need to make a database lookup to see if the value is valid. Since this tutorial hasn't treated database access yet, we will do a simpler example, but hopefully you will see that you can do just about everything with the CustomValidator. The control allows you to validate both clientside and serverside, where the serverside approach is probably the most powerful. Of course, doing serverside validation requires a postback to validate, but in most cases, that's not really a problem. 

In this example, we will simply check the length of the string in the TextBox. This is a very basic and that useful example, only made to show you how you may use the CustomValidator.
Custom text:<br />
<asp:TextBox runat="server" id="txtCustom" />
<asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtCustom" onservervalidate="cusCustom_ServerValidate" errormessage="The text must be exactly 8 characters long!" />
<br /><br />
As you can see, it's pretty simple. The only unknown property is the onservervalidate event. It's used to reference a method from CodeBehind which will handle the validation. Switch to our CodeBehind file and add the following method:
protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
    if(e.Value.Length == 8)
        e.IsValid = true;
    else
        e.IsValid = false;
}
This is very simple. The validator basically works by setting the e.IsValid boolean value to either true or false. Here we check the e.Value, which is the string of the control being validated, for it's length. If it's exactly 8 characters long, we return true, otherwise we return false.

No comments:

Post a Comment