Nikolaos Kantzelis ASP.Net Blog

This blog will focus on ASP.NET Framework

Sponsors

About Me

Great Blogs

Performing Validation using the JQuery Validation library/plugin

This another post that is focusing on how to use JQuery in ASP.Net applications. If you want to have a look at the other posts related to JQuery in my blog click here

In this post I would like to show you how to perform client-side validations using the JQuery validation plugin.

Some basic level of knowledge of JQuery is assumed.

Sadly, we canot cover the basics of JQuery in this post so here are a few resources for you to focus on

 You can download the Jquery Validation plugin from here.We will use only the jquery.validate.js file from the downloaded files.

If you want to have a look at some other posts of mine regarding validation using the ASP.Net validation controls have a look in this and also this post.

1) Launch Visual Studio 2010. I have Visual Studio 2010 ultimate edition but Express edition will also work. Create an ASP.Net Web site.Give your site an appropriate name.

2) We want to download and use the latest version of JQuery. We need to download it first. Then we need to remove the version that ships with VS 2010, 1.4.1.We will place inside the Scripts folder the 1.7 version of the JQuery library.

3)  Add a new item to your site, a web form. Name it, Validation.aspx. This is the markup inside the body tag:

 

<form id="frmMain" runat="server">
 <fieldset>
   <legend>Please provide your information</legend>
    <p>
<label for="txtName">Name</label>
<input id="txtName" name="txtName" type="text" class="input" />
</p>
	<p>
<label for="txtUsername">Username</label>
<input id="txtUsername" name="txtUsername" />
	</p>
	<p>
	<label for="pwdPassword">Password</label>
<input id="pwdPassword" name="pwdPassword" type="password" />
	</p>
	<p>
	<label for="pwdConfirmPassword">Confirm password</label>
<input id="pwdConfirmPassword" name="pwdConfirmPassword" type="password" />
		</p>
		<p>
	<label for="txtEmail">Email</label>
	<input id="txtEmail" name="txtEmaill" class="input" />
		</p>
		<p>
	<label for="txtURL">URL</label>
	<input id="txtURL" name="txtURL" class="input" />
		</p>
 
        <p>
         <label for="dotnetlanguage">Preferred .Net Language</label>
        <input id="csharp" name="dotnetlanguage" type="radio" value="0" />
                <label id="csharp_l" for="csharp_c">C#</label>
	<input id="vbnet" name="dotnetlanguage" type="radio" value="1"  />
 <label id="vb_l" for="vb.net">VB</label>
        
        </p>
		<p>
	<label id="lblComment" for="txtComment">Comments</label>
	<textarea id="txtComment" name="txtComment" rows="5" cols="55"></textarea>
		</p>
 
        <p>
        <label for="VSversion">Visual Studio Version you are using</label><br/>
  <input name="vsversion[]" id="1" value="1" type="checkbox" /> <label for="1">
VS 2010</label><br/>
  <input name="vsversion[]" id="2" value="2" type="checkbox" /> <label for="2">
VS 2008</label><br/>
  <input name="vsversion[]" id="3" value="3" type="checkbox" /> <label for="3">
VS 2005</label><br/>
        
        </p>
		<p>
<label for="chkAgree">Please agree to Terms and Conditions: </label>
<input type="checkbox" class="checkbox" id="chkAgree" name="chkAgree" />
		</p>
		<p>
	<input type="submit" value="Submit"/>
		</p>
	</fieldset>
	</form>

 

5) Let me explain what the form looks like. This is a typical form. It has fields like Name which is a required field.It has also a UserName field that is required and has at least 8 characters.Then we have two password fields. The password field and the confirm password field must be at least 6 characters and match.An Email field is also required and must be valid.A URL field is not required but if the user chooses to fill in the URL field that must be a valid URL. We have radio button fields , that the user must at least select one option. Then we have 3 checkbox fields and the user must choose at least one. Finally there is a checkbox field that must be checked (terms and conditions)

As you can see these are all items of a typical form.

We will check for those conditions using JQuery.

6) In the head section of the .aspx page add a reference to the following .js files

<script src="Scripts/jquery-1.7.js" type="text/javascript"></script>
<script src="Scripts/jquery.validate.js" type="text/javascript"></script>

 

7) Also in the head section I will include some styles.We will use these styles to style various elements of the form and what the visual indication would be once the validation fails.In this case it would be a red border indicating the failed validation.

<style type="text/css">
		#frmMain {
			width600px;
		}
		#frmMain label {
			displayinline-block;
			width150px;
			vertical-aligntop;
			font-weightbold;
		}
		.input {
			width400px;
		}
		#frmMain label.error {
			margin-left155px;
			colorRed;
			font-weightnormal;
			width400px;
		}
		#frmMain input.error {
			border1px solid Red;
		}
	</style>

 

8) Now I will add again in the head section the javascript code that makes the validation possible.

	<script type="text/javascript">
	    $.validator.setDefaults({
submitHandler: function () { alert("We got your form data"); }
	    });
 
	    $(function () {
	        $('#frmMain').validate({
	            rules: {
	 txtName: "required",
	 txtUsername: { required: true, minlength: 8 },
	 pwdPassword: { required: true, minlength: 6 },
pwdConfirmPassword: { required: true, minlength: 6, equalTo: '#pwdPassword' },
	 txtEmail: { required: true, email: true },
	 txtURL: { url: true },
	 chkAgree: { required: true },
	 dotnetlanguage: { required: true },
	 'vsversion[]': { required: true, minlength: 1 }
	            },
 
	            messages: {
	   txtName: "Please enter your first and last names.",
	   txtUsername: { required: 'Please enter a username.',
	   minlength: 'The username must be at least eight characters long.'
	                },
	   pwdPassword: {
	   required: 'You must enter a password.',
	   minlength: 'The password must be at least 6 characters long.'
	                },
	   pwdConfirmPassword: {
	   required: 'You must enter a confirmation password.',
	   minlength: 'The password must be at least 6 characters long.',
	   equalTo: 'The two passwords you enter must match.'
	                },
	   txtEmail: 'Please enter a valid email address.',
	   dotnetlanguage: 'Choose your favourite .Net Language',
           'vsversion[]''Select at least one option',
	   chkAgree: 'You must agree to the usage policy.'
          
	            }
	        });
 
	        $('#txtUsername').focus(function () {
	            var name = $('#txtName').val();
	            name = name.replace(' ''');
	            name = name.toLowerCase();
	            if (name && !this.value)
	                this.value = name;
	        });
	    });
	</script>

9) Let me explain what I am doing with the JQuery above

 $.validator.setDefaults({
submitHandler: function () { alert("We got your form data"); }
	    });

In this bit of code we have a custom function that runs an alert box when the data is successfully posted.

Then I use the JQuery ready function to set up validation rules and messages

<snippet>

 

 $(function () {
	        $('#frmMain').validate({
	            rules: {
                        txtName: "required",
	                txtUsername: { required: true, minlength: 8 }, 

 

 ......

 

 messages: {
	     txtName: "Please enter your first and last names.",
	  txtUsername: { required: 'Please enter a username.',
minlength: 'The username must be at least eight characters long.'
	                },

 

</snippet>

 

Rules and messages are passed as arguments to the validate method.

With the rules you can set up very easily the various validation criteria the validation process must conform to.You can see how we set up the required fields and the minimum length for a field. You can also see how we check for valid emails and urls.You can also see how we set up the validation for passwords that must match and various radio (one must be selected) and checkbox controls(one must be selected from the first set of checkboxes and then the final checkbox must be checked).Have a look below. There is nothing difficult really.

    $('#frmMain').validate({
	            rules: {
	                txtName: "required",
	                txtUsername: { required: true, minlength: 8 },
	                pwdPassword: { required: true, minlength: 6 },
pwdConfirmPassword: { required: true, minlength: 6, equalTo: '#pwdPassword' },
	                txtEmail: { required: true, email: true },
	                txtURL: { url: true },
	                chkAgree: { required: true },
	                dotnetlanguage: { required: true },
	                'vsversion[]': { required: true, minlength: 1 }
	            },

 

Have a look at the jquery.validate.js to see how these methods are implemented. Have a look at the minlength validation method in the jquery.validate.js method.

minlength: function(value, element, param) {
	return this.optional(element) || 
this.getLength($.trim(value), element) >= param;
		},

 

 

In the messages section we can set up the various text messages printed on the screen whenever the validation fails.

 messages: {
    txtName: "Please enter your first and last names.",
    txtUsername: { required: 'Please enter a username.',
    minlength: 'The username must be at least eight characters long.'
	},
     pwdPassword: {
   required: 'You must enter a password.',
   minlength: 'The password must be at least 6 characters long.'
	   },
   pwdConfirmPassword: {
  required: 'You must enter a confirmation password.',
 minlength: 'The password must be at least 6 characters long.',
 equalTo: 'The two passwords you enter must match.'
	   },
   txtEmail: 'Please enter a valid email address.',
  dotnetlanguage: 'Choose your favourite .Net Language',
  'vsversion[]''Select at least one option',
  chkAgree: 'You must agree to the terms and conditions.'
          
}
 });
 
  $('#txtUsername').focus(function () {
	     var name = $('#txtName').val();
	     name = name.replace(' ''');
	     name = name.toLowerCase();
	      if (name && !this.value)
	      this.value = name;
	        });

 

Finally when the username field gets the focus I am "suggesting"  a username by concatenating the first and last name of the first field. I also strip out all spaces and make them lowercase.

There is nothing difficult here.That is the magic of JQuery. Once you get your head around JQuery you can see how simple it is to use it.You can write very little code but it is so powerful.

10) Run your application and play around with the various validation fields. Make sure you fail the validation and see how JQuery picks up all the errors. Finally submit the form with no errors.

That is all folks.

Email me if you need the source code.

Hope it helps!!!

Comments

Gracye said:

Intelligence and simcpliity - easy to understand how you think.

# December 13, 2011 11:23 PM

Tipton said:

I don’t ordinarily comment in spite of this I gotta say regards

for that the post on this great one : D.

# October 7, 2012 10:57 PM