We can use CustomValidator to write our own complex validation at server side. Suppose we have to validate a phone number should be of 10 digit only so for that we can write a C# code to check lenth of phone number and if its not 10 digit just assign false to IsValid property.
args.IsValid = false;
How to use CustomValidator to write oun validation script in ASP.NET Example:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" >
<script runat="server">
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
if (args.Value.ToString().Length != 10)
{
args.IsValid = false;
}
}
</script>
<html>
<body>
<form id="Form1" runat="server">
<h4>
Check for Phone Number Length Validation</h4>
<br />
<br />
Phone Number:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" Text="Validate" runat="server" />
<br />
<br />
<asp:CustomValidator ID="CustomValidator1" ControlToValidate="TextBox1" Text="Phone Number of 10 digits are allowed only."
runat="server" OnServerValidate="CustomValidator1_ServerValidate" />
</form>
</body>
</html>
No comments:
Post a Comment