Friday 28 December 2012

Validation - CustomValidator in asp.net

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. 

Although the serverside approach is probably the most powerful, you need to consider your site hosting, especially if your database receives plenty of queries. 


Properties






Example

CustomValidator
Declare two Label controls, one TextBox control, one Button control, and one CustomValidator control in an .aspx file. The user() function checks the length of the input value. If the length is <8 or >16 the text "A username must be between 8 and 16 characters!" will appear in the CustomValidator control.







No comments:

Post a Comment

If any doubt?then please comment in my post

How to reduce angular CLI build time

 Index: ----- I am using angular cli - 7 and I am going to tell how to reduce the build time as per my knowledge. Problem: -------- Now the ...