Custom Validator: Server Side validation using Custom Validator in ASP.NET (C# & Vb.NET).

Aman Sharma
0
Custom Validator in ASP.NET:
In this article we will learn how to use custom validator in ASP.Net Applications. I will Use Custom Validator   OnServerValidate Event and perform validation on Server Side in ASP.Net using C# and VB.Net.


Demo:

In this example I will validate TextBox control and check whether entered Email Id is Valid or not. I will use  OnServerValidate Event of custom validator.

Design your Page i.e. Design Section:       

Enter Email:<asp:TextBox ID="txtEmail" runat="server" Width="200px"></asp:TextBox>
 <br />      
 <br />

 <asp:Button ID="btnEmail" runat="server"  Text="Validate Email"  />
                       
 <br />
              
 <asp:CustomValidator ID="CustomValidator1" runat="server"                    
 ErrorMessage="Email Id Is not Valid"                   
 OnServerValidate="IsEmailValid"                     
 ClientValidationFunction="" ForeColor="#990000">
</asp:CustomValidator>


When we press the button, OnServerValidate Event of custom validator will be handled. In this Event handler I have used Regular Expression to validate data of text box.
We will validate the data using IsMatch() method of Regular Expression RegEx.  Result of IsMatch() method  i.e. True or False, will be passed to Isvalid property of ServerValidateEventArgs. If isvalid property is false then error message will be displayed otherwise Email Id is Valid.

Asp.Net Code:
Using C#:

public void IsEmailValid(object sender, ServerValidateEventArgs e)
    {
        string strRegex = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}" + "\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\" + ".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Regex re = new Regex(strRegex);
        e.IsValid = re.IsMatch(txtEmail.Text);       
    }


Using Vb.net:

Public Sub IsEmailValid(sender As Object, e As ServerValidateEventArgs)
    Dim strRegex As String = "^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" + "\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" + ".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
    Dim re As New Regex(strRegex)
    e.IsValid = re.IsMatch(txtEmail.Text)
End Sub



In this section we have learned how to use Custom validator in ASP.NET. if you have any query then you can ask by leaving your query in comment section.

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !