November 1, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Validation using jQuery in ASP.NET Applications

  • September 12, 2011
  • By Srinath MS
  • Send Email »
  • More Articles »

jQuery is the concise JavaScript library that makes your client-side code interactive with less pieces of code stitched together. It’s easy to grasp this language in a similar fashion to JavaScript. It has a simplified event handling model with a tiny footprint.

jQuery has received significant attention from many folks now, including Microsoft, which brought it to the ASP.Net MVC framework.

Getting Into jQuery Validation

The script below shows how a submit button click can be triggered to validate if the user has entered an email address.

<script type="text/javascript">
$(document).ready(function()
{ 
     $('#button-save).click(function() 
{  
        var emailAddressValue = $("#textboxEmailAddress").val();
        if(emailAddressValue == '') {
$("#textboxEmailAddress ").after('<span class="error">Please specify an email address.</span>');
return false;
        	}
 
    });
});
</script>

The .val() method is used to retrieve the values from the form object. It returns single/multiple values depending on the form object that is used. The after() method instructs to insert the specified html after the object that the select expression retrieves.

jQuery supports a Full-Featured and flexible Validation plug-in that lets you easily hook it to ASP.Net applications. . The jQuery validation plugin leverages a CSS selector like syntax to apply a set of validation rules. You can download the plugin (js) file from jQuery website.

Refer it in your web application with the script tag as follows:

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

A sample validate function that validates a required field is shown below (It is a simple form with username, password, confirm password and email fields):

<script type="text/javascript">
$(document).ready( function() {
               $("#formName").validate({
                           rules:{
                                           username:{
                                                               required:true,
                                                               minlength:10
                                           },
                                           password:{
                                                               required:true,
                                                               minLength:5
                                           },
                                           confirm_password:{
                                                               required:true,
                                                               minlength:5,
                                                               equalTo:"#password"
                                           },
                                           email:{
                                                               required:true,
                                                               email:true
                                           },
},
                            messages:{
                                           username:{
                                                         required: “Please specify a username",
                                                         minLength:"The username is too short"
                                           },
                                           password:{
                                                          required:"Please specify a password"
                                           minLength:"The password is too short"
                                           },
                                           confirm_password:{
                                                  required:"Please provide a password",
                                                  minLength:"The password is too short",
                                                  equalTo: "Please specify the same password as above"
                                           },
                                           email: "This is not a valid email address.",
                                                       }
               });
        }
</script>

The password and confirm password objects are matched by the validation plugin for you and shows the message on the equalTo attribute if they don’t match. The validation logic seems to be unified and totally configurable at one place.

For your ASP.Net objects, you can set the validation CSS classes that will trigger the validations, like below. The class data offers the metadata for the library to validate the data for you.

<input type="text" name="nameoftheTextBox" id="idofTheTextBox" class="required email" />

The class “required” checks if the input element has value in it. Similarly, the validation scripts provide us the email, password, URL and many other validation css elements. It supports other validations like digits, date, min, max as well.

This plugin offers you many useful validation methods like Email validation and also lets you write methods on your own. If you want to display specific error messages for the validations, use the “Messages” parameter.

The messages that appear as errors are in English and there are translations also available in many other locales. From MSDN, “To support validation for non-English locales in ASP.NET MVC 3 applications, you must include a locale-specific jQuery methods script file for each language you support." You can download these scripts here.

For example, for German locales, use the following file from the URL listed previously:

jquery.validate_17\jquery-validate\localization\methods_de.js”

You can also use dynamically add the rules to an object. jQuery lets you query using “class” names, like in the following example, and lets you control the missing input.

<script type="text/javascript">
$(document).ready(function() {
$("#formname").validate();
});

$('.email).rules('add', { 
        required: true, 
        messages: { 
            required: Please share your email-id.' 
        } 
    });
});
</script>

<input name="textboxEmailAddress" type="text" id="textboxEmailAddressId" class=" email” />

Note that the last two code samples (shown above) indicate that whenever the form is submitted through any control, the validation would happen. You do not want this to happen, especially when you have multiple submit buttons on a single form. So the best way is to trigger the Validate functions from the button click events, like this:

$("#submitButton").click(function() {
  return $("# formname ").valid();
});

Note that you should also disable the form submit in the form validate function like below:

$(document).ready(function() {
$("#formname").validate({onsubmit: false});
});

ASP.Net MVC supports the client side validation using the Model validation that is specified through the Object attributes in the Model. If you want to replace the client-side validations with jQuery , all you have to do is:

a) Refer the jQuery validate and the MicrosoftMvcJQueryValidation JavaScript files.
b) And add the “Html.EnableclientValidation()” code in the view. 

There are more beautiful validation workflows that can be implemented using jQuery. Here are few from my bookmarks:

But do remember that you have to continue to do server-side validation to ensure that you ASP.Net applications are foolproof.

REFERENCES


Tags: ASP.NET, jQuery, validation, tutorial

Originally published on http://www.developer.com.


Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel