X

Subscribe To Our Mailing List

P.S I will never spam you...100% GUARANTEED!

Wednesday, December 17, 2014

jquery validation - Client side validation using jquery in asp.net mvc

Introduction for "client side validation using jquery in asp.net mvc"

In most of the cases we are going to use Data Annotations for validation in MVC. Let's not forget the point of unobtrusive client-side validation which turned out to be a boon for the developers. In unobtrusive client-side validation, validation rules are defined using attributes added to the generated HTML elements. This article will focus on adding the validation rules from client side.

client side validation using jquery in asp.net mvc
Let's get started

Now let's dive into the code part as how we can add the rules for the controls. Before that i need to discuss when we can use this type of approach – Consider a scenario where you are re-using the page with hide and show the controls of the page, eg : if one client wants textbox and another client wants dropdownlist for the same field in a same page and if the validation rules are different for both these controls then adding the rules from client side would be a better approach.

For enabling client side validation, we required to include following scripts in our view or layout page in the following order.

<script src="~/Scripts/jquery-{version}.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>

Now lets create a new project for this and lets add the controller, models, views and javascript for our project.

  1. Create a new MVC project 
  2. Add a new controller called "ProductController"
  3. Add a new model called "ProductModel" and add the properties - Name, Description and Amount
  4. Add a new view called "Index.html" for our product
  5. Add a new javascript file for validation "productvalidation.js"

Now we will just set the validation rules for all the properties in the ProductModel in productvalidation.js file. Script for adding the validation rules for our controls in a page -

$(document).ready(function () {

    var regexAlpabetsOnly = /^[a-zA-Z\- ']*$/;
    var regexNumbersOnly = /^\d+$/;
   
    $('#Name').rules("add", {
       required: true,
       minlength: 2,
       messages: {
         required: "Please enter name",
         minlength: "At least 2 characters are mandatory"
       }
   });

   $('#Description').rules("add", {
      required: true,
      regex: regexAlpabetsOnly,
      maxlength : 20,
      messages: {
        required: "Please enter description",
        regex: "Please enter alphabets in description field",
        maxlength: "Exceeded maximum length of description"
      }
  });

   $('#Amount').rules("add", {
      required: true,
      regex: regexNumbersOnly,
      messages: {
        required: "Please enter Amount",
        regex: "Please enter numbers in amount field"
      }
   });

 });

As you see above nothing fancy all are straight forward and we have following validations -

  • For "Name" property we are adding required field validation and minimum length validation.
  • For "Description" property we are adding required field validation and regex validation to allow only alphabets.
  • For "Amount" property we are adding required field validation and regex validation to allow only numbers.

All are fine but only concern here is error messages are hardcoded. So its always a better idea to get these texts from resource file instead of hardcoding.

Now lets add the resource file and move these texts into resource file. For brevity i have not given the lump steps here -

Once its added the next would be to get the resource file data to javascript and that again is easy. Better option to do this is serialize the resource file and pass the JSON object to javascript.

Lets do that now -

In Controller lets add a method which will return JSON object -

[HttpGet]
public JavaScriptResult GetResourceFileData()
{
 return ResourceSerialiser.GetResourceSerailizedData(Resource.ResourceManager);
} 

For Serializing the resource file data -
 
public static JavaScriptResult GetResourceSerailizedData(ResourceManager resourceManager)
  {
     string cacheName = string.Format
       ("ResourceJavaScripter.{0}", CultureInfo.CurrentCulture.Name);

     JavaScriptResult value = HttpRuntime.Cache.Get(cacheName) as JavaScriptResult;

     if (value == null)
     {
        JavaScriptResult javaScriptResult = CreateResourceJSON(resourceManager);
        HttpContext.Current.Cache.Insert(cacheName, javaScriptResult);
        return javaScriptResult;
     }

      return value;
  }

  static JavaScriptResult CreateResourceJSON(ResourceManager resourceManager)
  {
       ResourceSet defaultSet = resourceManager.GetResourceSet
             (CultureInfo.GetCultureInfo("en"), true, true);
       ResourceSet resourceSet = resourceManager.GetResourceSet
             (CultureInfo.CurrentCulture, true, true);

       var resourceBaseName = resourceManager.BaseName;
       var jsonObjectName = resourceBaseName.Substring(resourceBaseName.LastIndexOf(".") + 1);

       StringBuilder sb = new StringBuilder();
       sb.Append("[");
       sb.Append("{");

       foreach (DictionaryEntry dictionaryEntry in resourceSet)
            if (dictionaryEntry.Value is string)
           {
                string value = resourceSet.GetString
                    ((string)dictionaryEntry.Key) ?? (string)dictionaryEntry.Value;
                sb.AppendFormat("\"{0}\":\"{1}\"", dictionaryEntry.Key, Encode(value));
                sb.Append(",");
           }


        string script = sb.ToString();
        if (!string.IsNullOrEmpty(script)) 
             script = script.Remove(script.Length - 1);


        script += "}]";
   

        JavaScriptResult result = new JavaScriptResult { Script = script };
        return result;
    } 

    static string Encode(string val)
    {
         val = (val).Replace("\"", "\\\"").Replace('{', '[').Replace('}', ']');
         val = val.Trim();
         val = System.Text.RegularExpressions.Regex.Replace(val, @"\s", " ");
         return val;
    }

In javascript lets add a new AJAX call to get the JSON object from controller method -

$.ajax({
  cache: false,
  type: "GET",
  url: "Product/GlobalResourceFileData",
  async: false, 
  dataType: "json",
  success: function (resourceData) {
   resourceFilevalues = resourceData[0];
  }
 });

" resourceFilevalues " is global variable which is used to receive the JSON object in AJAX call given above.

Now the hardcoded values will be replaced by the resource file properties like below -

$('#Name').rules("add", {
  required: true,
  minlength: 2,
  messages: {
   required: resourceFilevalues.NameRequiredErrMessage,
   minlength: resourceFilevalues.NameMinLengthErrMessage
  }
 });

 $('#Description').rules("add", {
  required: true,
  regex: regexAlpabetsOnly,
  maxlength : 20,
  messages: {
   required: resourceFilevalues.DescriptionRequiredErrMessage,
   regex: resourceFilevalues.DescriptionRegexErrMessage,
   maxlength: resourceFilevalues.DescriptionMaxLengthErrMessage
  }
 });

 $('#Amount').rules("add", {
  required: true,
  regex: regexNumbersOnly,
  messages: {
   required: resourceFilevalues.AmountRequiredErrMessage,
   regex: resourceFilevalues.AmountRegexErrMessage
  }
 });

So hope this article is useful and i agree this is the longest post i have written :-)


No comments:

Post a Comment

Comments Section