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.



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: