21 November 2013

Explain about Custom Validator control in asp.net

In this post we will discuss about Custom Validator control in asp.net.

You can also check my previous articles on RequiredFieldValidator, RangeValidator, RegularExpressionValidator,comparevalidator control examples in Asp.Net.

The CustomValidator control allows you to write a method to handle the validation of the value entered.

Properties :
1.Display : The display behavior for the validation control. Legal values are:
  • None (the control is not displayed. Used to show the error message only in the ValidationSummary control)
  • Static (the control displays an error message if validation fails. Space is reserved on the page for the message even if the input passes validation.
  • Dynamic (the control displays an error message if validation fails. Space is not reserved on the page for the message if the input passes validation
2.Error Message :
The text to display in the ValidationSummary control when validation fails. Note:This text will also be displayed in the validation control if the Text property is not set.

code :

<script  runat="server">
Sub user(source As object,args As ServerValidateEventArgs)
   if len(args.Value)<8 or len(args.Value)>16 then
    args.IsValid=false
   else
    args.IsValid=true
   end if
End Sub
</script>    

<!DOCTYPE html>
<html>
<body>

<form runat="server">
<asp:Label runat="server" Text="Enter a username: " />
<asp:TextBox id="txt1" runat="server" />
<asp:Button Text="Submit" runat="server"/>
<br>
<asp:Label id="mess" runat="server"/>
<br>
<asp:CustomValidator
ControlToValidate="txt1"
OnServerValidate="user"
Text="A username must be between 8 and 16 characters!"
runat="server"/>
</form>

</body>
</html>


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 as shown below :







No comments:

Post a Comment