How to use CustomValidator control in ASP.NET 4.0

You can use the CustomValidator control to execute your custom client-side and server-side validation routines. You can associate them with the control so that validation is performed automatically. If the validation fails, the Page.IsValid property is set to false, as occurs with any other validation control.

 

The client-side and server-side validation routines for the CustomValidator are declared similarly. They both take two parameters:

– A reference to the validator

– A custom argument object. The custom argument object provides:

– A Value property that contains the current value of the associated input control (the value you have to validate)

–  An IsValid property through which you specify whether the input value is valid.

If you want to check that a number is a multiple of seven, for example, you could use a client-side JavaScript validation routine like this:

 

<script type=”text/javascript”>

function CustIDClientValidate(ctl, args)

{

// the value is a multiple of 7 if the modulus by 7 is 0

args.IsValid=(args.Value%7 == 0);

}

</script>

 

To associate this code with the control so that client-side validation is performed automatically, you should set the ClientValidationFunction to the name of the function (in this case, CustIDValidate). When the page is posted back, ASP.NET fires the CustomValidator.ServerValidate event. You can handle this event to perform the same task by using C# or Visual Basic code. The JavaScript logic is optional. You must include a server-side validation routine to ensure the validation is performed even if the client is using a down-level browser. The next code lines present the event handler for the ServerValidate event. It performs the C# equivalent of the JavaScript client-side validation routine shown earlier:

 

protected void CustIDServerValidate(object sender, ServerValidateEventArgs args)

{

try

{

args.IsValid = (int.Parse(args.Value)%7 == 0);

}

catch

{

// An error is most likely caused by non-numeric data.

args.IsValid = false;

}

}

 

The next code lines show CustomValidator tag that uses these routines:

 

<asp:TextBox runat=”server” ID=”CustID” />

<asp:CustomValidator runat=”server” ControlToValidate=”CustID ”

ClientValidationFunction=”CustIDClientValidate” OnServerValidate=”CustIDServerValidate”

ErrorMessage=”ID must be a multiple of 7″ Display=”dynamic”>*

</asp:CustomValidator>