jQuery and ASP.NET

August 30, 2009

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.



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Handle Server and Client Side Validation using the ASP.NET Custom Validator control"
 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions