Using client-side validation in ASP.NET CustomValidator control

CustomValidator server control in ASP.NET is used to validate an input control using a custom function. It provides programmer with the flexibility to use a custom function for validating an input control. CustomValidator can validate a control using a server-side function or a client-side function. Server-side function is written in server side language like Visual C#, Visual Basic etc and client-side function is written using a client side language like Javascript.

Properties of CustomValidator control

Property Uses
ControlToValidate Gets or sets the name of the control to validate
ClientValidationFunction Gets or sets the name of the client-side function used for validation
ValidateEmptyText Gets or sets a Boolean value which specifies whether it will validate empty text or not. It is set to “true” to validate an empty text
Display Gets or sets the display type of the error message. It can be set to Dynamic, Static or None
ErrorMessage Gets or sets error message displayed when validation fails

Note: OnServerValidate is set to the server-side function name used to validate on the server side

Example: Client-side validation using CustomValidator control

<asp:TextBox ID="txtUserName" runat="server">
</asp:TextBox>

<asp:CustomValidator
     ID="cvUserName"
     runat="server"
     ErrorMessage="Invalid User Name"
     ControlToValidate="txtUserName"
     ClientValidationFunction="ValidateUserName"
     ForeColor="Red"
     ValidateEmptyText="true"
     Display="Dynamic">
</asp:CustomValidator>

<script type="text/javascript">
    function ValidateUserName(source, arguments) {
        if (arguments.Value.length >= 8 && arguments.Value.length<=15) {
            arguments.IsValid = true;
        }
        else {
            arguments.IsValid = false;
        }
    }
</script>

Leave a Reply

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