Handle Server and Client Side Validation using the ASP.NET Custom Validator control

I have seen a lot of users asking how to use the CustomValidator Control to perform both client side validation as well as server side validations. Let us explore how with a practical example. In this example, we will keep a Checkbox inside a Form. The user has to keep the CheckBox in a checked state before the form is submitted. Here’s how to achieve this requirement:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title>Validate if CheckBox is not Checked</title>
<
script type="text/javascript">
function
chkBoxClientVal(sender, e) {
var ctrl = document.getElementById('<%= CheckBox1.ClientID %>');
e.IsValid = ctrl.checked;
}
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:CheckBox ID="CheckBox1" runat="server" />
<
asp:CustomValidator runat="server" ID="CustomChkBox"
EnableClientScript="true"
ClientValidationFunction="chkBoxClientVal"
OnServerValidate="chkBoxServerVal"
SetFocusOnError="true">
Check Box To Be Checked</asp:CustomValidator>
<
asp:Button ID="Button1" runat="server" Text="Button" />
</
div>
</
form>
</
body>
</
html>

C#

protected void chkBoxServerVal(object sender, ServerValidateEventArgs e)
{
e.IsValid = CheckBox1.Checked;
}

VB.NET

Protected Sub chkBoxServerVal(ByVal sender As Object, _
ByVal e As ServerValidateEventArgs)
e.IsValid = CheckBox1.Checked
End Sub

Observe the following:

- EnableClientScript is set to true

- EnableClientScript has not effect if a JavaScript function does not exists

- The ClientValidationFunction must consists a JavaScript function of the form

Function SomeFunction(source, args)

Note: As a best practice, always remember to validate ServerSide in addition to Client Side Validation. This helps maintain validation rules when JavaScript is turned off.






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: