Using the CustomValidator Control

The CustomValidator control in ASP.NET provides a way to perform customized validation on both the client-side and server-side. It allows you to define your own validation logic for a specific scenario that may not be covered by the built-in validation controls.

To use the CustomValidator control, you can create a validation control that checks the entered value against your specific criteria. For example, you can create a validation control that verifies if a text box value is at least 8 characters long. By associating this validation control with the CustomValidator control, you can trigger the validation process.

CustomValidator control

The CustomValidator control supports both client-side and server-side validation. The client-side validation is performed using JavaScript, which allows for immediate feedback to the user without requiring a round-trip to the server. On the other hand, server-side validation provides more robust validation by validating the input on the server before processing it. This ensures that the validation is enforced even if the client-side validation is bypassed or disabled.

To implement server-side validation with the CustomValidator control, you need to handle the ServerValidate event. In the event handler, you can write custom code to perform the validation logic based on your specific requirements. If the validation fails, you can set the IsValid property of the CustomValidator control to false, indicating that the input is invalid. Code
< asp:TextBox runat="server" id="txtCustomValidator" / > < asp:CustomValidator runat="server" id="cusCustomTxt" controltovalidate="txtCustomValidator" onservervalidate="cusCustomTxt_ServerValidate" errormessage="Lebgth must be 8 or more characters..." / >
C# Code
protected void cusCustomTxt_ServerValidate(object sender, ServerValidateEventArgs e) { if(e.Value.Length >= 8) e.IsValid = true; else e.IsValid = false; }

The CustomValidator control provides a flexible and powerful mechanism to perform custom validation in ASP.NET. It allows you to create complex validation scenarios and enforce them both on the client-side and server-side. By using the ServerValidate event, you can write your own validation code and handle the validation process according to your application's needs.


If a client validation function is not associated with a CustomValidator control, the error message will not be rendered until the page is posted back to the server. This is because the other validation controls on the page prevent it from being posted if there are any validation errors. As a result, the error message generated by the CustomValidator control will only be displayed once all other validation checks on the page have been successfully passed.