Bookmark and Share

Thursday, November 11, 2010

JQuery: HOWTO Add Validator To Your Forms

Here is a simple way to add Input validation to your ASP.NET code using the JQuery Validator plugin.

1) Add a reference to the validator javascript library

<script src="scripts/jquery.validate.min.js" type="text/javascript"></script>


2) Add Css class to your input, example:


<asp:TextBox ID="txtFirstname" runat="server" Text='<%# Bind( "Firstname" ) %>' CssClass="required"></asp:TextBox>

or for a required email:

<asp:TextBox ID="txtEmail" runat="server" Text='<%# Bind( "Email" ) %>' CssClass="required email"></asp:TextBox>


3) Call the “validate” method:


$(document).ready(function() {
$("#aspnetForm").validate();
}


4) If you have custom regular expressions loaded from server you need to:


Add on the server side an attribute to the the text elements with the regular expression:

 

txtEmail.Attributes.Add("regexp", "your regular expression rule" );

Add a custom validator via Javascript:


$.validator.addMethod(
"regex",
function(value, element, regexp) {
var check = false;
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
'<%= GetRes("Your message from sderver") %>'
);


apply the validation rule to all elements with a “regexp” attribute existing:

if ($('INPUT[regexp]').length > 0) {
$('INPUT[regexp]').rules("add", { regex: $(this).attr('regexp') });
}









5) If you need to change the default validation messages you can use this code:


jQuery.extend(jQuery.validator.messages, {
required: '<%= GetRes("Your_String_Id") %>'
});

GetRes is an internal helper function, it loads a string from the resources.

 

Hope it helps!