In this article I will explain, how to use ASP.Net CustomValidator OnServerValidate Event and perform validation Server Side in ASP.Net using C# and VB.Net.
In this example I will validate TextBox data and make sure that the entered text is strictly numeric i.e. only numbers using ASP.Net Custom Validator and its OnServerValidate Server Side Event.
HTML Markup
The HTML Markup consists of an ASP.Net TextBox, its Associated CustomValidator and a Button control. For the CustomValidator Validate_Numeric Server Side event has been specified for validating the TextBox contents.
Enter Number:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" ForeColor="Red" ErrorMessage="Please enter numeric values."
OnServerValidate="Validate_Numeric" ControlToValidate="TextBox1"></asp:CustomValidator>
<br />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
Using the OnServerValidate event to perform validation Server Side in ASP.Net
When the Button is pressed, OnServerValidate event handler for the CustomValidator is executed. Inside the event handler, the TextBox Text is validated using Regular Expressions.
The result returned from the IsMatch function of the Regular Expression Regex method (True/False depending on the TextBox Text) is supplied to the IsValid property of the ServerValidateEventArgs Argument of the ASP.Net CustomValidator.
If the IsValid property is false then CustomValidator will display the error message set in its ErrorMessage property.
C#
protected void Validate_Numeric(object sender, ServerValidateEventArgs e)
{
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("^[0-9]+$");
e.IsValid = r.IsMatch(TextBox1.Text);
}
VB.Net
Protected Sub Validate_Numeric(sender As Object, e As ServerValidateEventArgs)
Dim r As New System.Text.RegularExpressions.Regex("^[0-9]+$")
e.IsValid = r.IsMatch(TextBox1.Text)
End Sub
Demo
Downloads