Server Side CustomValidator Example in Asp.Net C# VB.Net

Sometimes existing Asp.Net validation controls does not meet our requirements. In that case we can define custom validation function and call it using the CustomValidator control to check user input from server side. Please always do the server side validation along with client side validation to prevent users from bypassing validation by disabling or changing the client script. To use the CustomValidator control we need to know some important properties of this control like:

ControlToValidate: Need to define the input Control here like TextBox.
ErrorMessage: The message you want to show whenever validation fail.
OnServerValidate: This is the key property to validate a control from server side. Write a validation function over the targeted control and assign the function name here.
ValidationGroup: Need to provide a name if your page has different group of validations for different controls.

Related Article:
Client Side CustomValidator Example using Javascript in Asp.Net C# VB.Net

To do the Example use the below HTML markup:

Password: <br />
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Length must be >6 !!" ControlToValidate="txtPassword" OnServerValidate="validateLength" Font-Italic="true" Font-Bold="true" ForeColor="Red" ValidationGroup="Registration"></asp:CustomValidator><br />
Confirm Password:<br />
<asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password"></asp:TextBox><br /><br />
<asp:Button ID="Button1" runat="server" Text="Validate" ValidationGroup="Registration"/>

Create a server-based event handler for the control’s ServerValidate event. This event is called to perform the validation. The method has a signature such as the following:
C# Code:

protected void ValidationFunctionName(object source, ServerValidateEventArgs args)


VB.Net Code:

Protected Sub ValidationFunctionName(source As Object, args As ServerValidateEventArgs)

End Sub

Server Side function to Validate a TextBox Control using CustomValidator:
C# Code:

    protected void validateLength(object source, ServerValidateEventArgs args)
        args.IsValid = (args.Value.Length > 6);

VB.Net Code:

    Protected Sub validateLength(source As Object, args As ServerValidateEventArgs)
        args.IsValid = (args.Value.Length > 6)
    End Sub

Server Side CustomValidator Example in Asp.Net Csharp VB.Net

Hope now you can use CustomValidator from server side function.

Download Code Example C#        Download Code Example VB.Net

Posted in .Net,, C#, VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *