CustomValidator in Asp.net Text box Control

CustomValidator in Asp.net Text box Control:



CustomValidator:

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.



<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 />

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  simple Example. 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.


Other asp.net programming related Post:


Comments

Popular posts from this blog