<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Nadeem Khedr</title>
	<atom:link href="http://nadeemkhedr.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://nadeemkhedr.wordpress.com</link>
	<description></description>
	<lastBuildDate>Sun, 16 Jun 2013 19:30:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='nadeemkhedr.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Nadeem Khedr</title>
		<link>http://nadeemkhedr.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://nadeemkhedr.wordpress.com/osd.xml" title="Nadeem Khedr" />
	<atom:link rel='hub' href='http://nadeemkhedr.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Asp.net MVC JsonResult, Anonymous types and Testing</title>
		<link>http://nadeemkhedr.wordpress.com/2013/02/11/asp-net-mvc-jsonresult-anonymous-types-and-testing/</link>
		<comments>http://nadeemkhedr.wordpress.com/2013/02/11/asp-net-mvc-jsonresult-anonymous-types-and-testing/#comments</comments>
		<pubDate>Sun, 10 Feb 2013 22:05:14 +0000</pubDate>
		<dc:creator>Nadeem</dc:creator>
				<category><![CDATA[MVC]]></category>
		<category><![CDATA[asp.net-mvc]]></category>
		<category><![CDATA[unit-testing]]></category>

		<guid isPermaLink="false">http://nadeemkhedr.wordpress.com/?p=119</guid>
		<description><![CDATA[This article is an explanation on how to access the data from a JsonResult for using it in your unit testing The JsonResult type has a property called Data of type Object that you can parse if you have used a concrete object as your data for example: Model Controller Action Unit Test This is [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nadeemkhedr.wordpress.com&#038;blog=36720970&#038;post=119&#038;subd=nadeemkhedr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>This article is an explanation on how to access the data from a <em><span style="color:#993300;">JsonResult</span> for using it in your unit testing</em></p>
<p>The <span style="color:#993300;"><em>JsonResult</em> </span>type has a property called <em>Data</em> of type <span style="color:#993300;"><em>Object</em></span> that you can parse if you have used a concrete object as your data for example:</p>
<h3>Model</h3>
<pre class="brush: csharp; title: ; notranslate">
public class Person
  {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Age { get; set; }
  }
</pre>
<h3>Controller Action</h3>
<pre class="brush: csharp; title: ; notranslate">
public JsonResult Index()
{
  //Logic ....
  var person = new Person
                      {
                          Id = 1,
                          Name = &quot;Nadeem&quot;,
                          Age = &quot;24&quot;
                      };
  return Json(person);
}
</pre>
<h3>Unit Test</h3>
<pre class="brush: csharp; title: ; notranslate">
[Test]
public void Testing()
{
  var controller = new HomeController();

  var result = controller.Test();
  var data = result.Data as Person; //you can now access the Person properties

  //Assert
}
</pre>
<hr />
<p>This is all good but we get stuck if we want to pass an anonymous object to our <span style="color:#993300;"><em>JsonResult there is no way to cast to something to access an anonymous object properties<br />
</em></span></p>
<p>the solution is i made two custom helper methods that we can use to get values from a <em>JsonResult.Data</em> object<br />
ill follow after with an example of using it</p>
<h3>The custom helper:</h3>
<pre class="brush: csharp; title: ; notranslate">
public static class Helper
{
  public static object GetValue(this JsonResult result,string propertyName)
  {
    IDictionary&lt;string, object&gt; wrapper = new System.Web.Routing.RouteValueDictionary(result.Data);
    return wrapper[propertyName];
  }
  public static T GetValue&lt;T&gt;(this JsonResult result, string propertyName)
  {
    return (T) GetValue(result, propertyName);
  }
}
</pre>
<h2>Example:</h2>
<h3>Controller Action</h3>
<pre class="brush: csharp; title: ; notranslate">
public JsonResult Index()
{
  //Logic ....
  return Json(new {number = 1});
}
</pre>
<h3>Unit Test</h3>
<pre class="brush: csharp; title: ; notranslate">
[Test]
public void Testing()
{
  var controller = new HomeController();

  var result = controller.Index();

  Assert.AreEqual(1, result.GetValue&lt;int&gt;(&quot;number&quot;));
}
</pre>
<p>This is how to test a JsonResult using  anonymous types</p>
<p>&nbsp;</p>
<h3>For the fun of it we can make a helper that returns a dynamic type <span style="color:#888888;">(but its not as efficient as the top solution)</span></h3>
<h3>The custom helper:</h3>
<pre class="brush: csharp; title: ; notranslate">
public static dynamic ToDynamic(this JsonResult jsonResult)
{
  var expandoObject = new ExpandoObject();
  var expandoCollection = (ICollection&lt;KeyValuePair&lt;string, object&gt;&gt;)expandoObject;
  var dataWrapper = new RouteValueDictionary(jsonResult.Data);
  foreach (var kvp in dataWrapper)
  {
    expandoCollection.Add(kvp);
  }
  dynamic eoDynamic = expandoObject;
  return eoDynamic;
}
</pre>
<p>Unit Test</p>
<pre class="brush: csharp; title: ; notranslate">
[Test]
public void Testing()
{
  var controller = new HomeController();

  var result = controller.Index();

  Assert.AreEqual(1, result.ToDynamic().number);
}
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nadeemkhedr.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nadeemkhedr.wordpress.com/119/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nadeemkhedr.wordpress.com&#038;blog=36720970&#038;post=119&#038;subd=nadeemkhedr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nadeemkhedr.wordpress.com/2013/02/11/asp-net-mvc-jsonresult-anonymous-types-and-testing/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cb9c077b46a06bf0083e38fc7bc3d16a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nadeemkhedr</media:title>
		</media:content>
	</item>
		<item>
		<title>Knockout view model binding variations to a page</title>
		<link>http://nadeemkhedr.wordpress.com/2013/01/29/knockout-view-model-binding-variations-to-a-page/</link>
		<comments>http://nadeemkhedr.wordpress.com/2013/01/29/knockout-view-model-binding-variations-to-a-page/#comments</comments>
		<pubDate>Tue, 29 Jan 2013 21:22:53 +0000</pubDate>
		<dc:creator>Nadeem</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[bindings]]></category>
		<category><![CDATA[knockout]]></category>
		<category><![CDATA[mvvm]]></category>

		<guid isPermaLink="false">http://nadeemkhedr.wordpress.com/?p=106</guid>
		<description><![CDATA[Bind a view model to the whole page First of lets start with a simple example and how to write a simple view model and bind it to the page And the Javascript file This will bind our Javascript view model to the whole html document and every variable in the databind attributes wil refer [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nadeemkhedr.wordpress.com&#038;blog=36720970&#038;post=106&#038;subd=nadeemkhedr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<h1>Bind a view model to the whole page</h1>
<p>First of lets start with a simple example and how to write a simple<em> view model</em> and bind it to the page</p>
<pre class="brush: xml; title: ; notranslate">
First name: &lt;input type=&quot;text&quot; data-bind=&quot;value: firstName&quot; /&gt;

Last name: &lt;input type=&quot;text&quot; data-bind=&quot;value: lastName&quot; /&gt;

&lt;h2&gt;Hello, &lt;span data-bind=&quot;text: fullName &quot;/&gt;!&lt;/h2&gt;
</pre>
<p>And the Javascript file</p>
<pre class="brush: jscript; title: ; notranslate">
var User = function() {
    this.firstName = ko.observable(&quot;Nadeem&quot;);
    this.lastName = ko.observable(&quot;Khedr&quot;);
    this.fullName = ko.computed(function () {
      return this.firstName() + &quot; &quot; + this.lastName();
    },this);
};
ko.applyBindings(new User());
</pre>
<p>This will bind our <em>Javascript</em> view model to the whole <em>html</em> document and every variable in the <em>databind</em> attributes wil refer to a property of this one view model</p>
<h1>Bind a <em>view model</em> to a partial part of the page</h1>
<p>In the previous example we passed our <em>view model</em> to <em><span style="color:#993300;">ko.applyBindings</span></em>, this method take another parameter, which is the <em>DOM</em> element that we want to attach our<em> view model</em> to, In the next example we will attach two different &amp; not related<em> view models</em> to different parts of our page</p>
<pre class="brush: xml; title: ; notranslate">

&lt;div id=&quot;section1&quot;&gt;
  First name: &lt;input type=&quot;text&quot; data-bind=&quot;value: firstName&quot; /&gt;

  Last name: &lt;input type=&quot;text&quot; data-bind=&quot;value: lastName&quot; /&gt;

  &lt;h2&gt;Hello, &lt;span data-bind=&quot;text: fullName &quot;/&gt;!&lt;/h2&gt;
&lt;/div&gt;
&lt;div id=&quot;section2&quot;&gt;
First name: &lt;input type=&quot;text&quot; data-bind=&quot;value: firstName&quot; /&gt;

Last name: &lt;input type=&quot;text&quot; data-bind=&quot;value: lastName&quot; /&gt;

&lt;h2&gt;Hello, &lt;span data-bind=&quot;text: fullName &quot;/&gt;!&lt;/h2&gt;
&lt;/div&gt;
</pre>
<p>And the <em>Javascript</em> for this</p>
<pre class="brush: jscript; title: ; notranslate">
var User = function(firstName,lastName) {
    this.firstName = ko.observable(firstName);
    this.lastName = ko.observable(lastName);
    this.fullName = ko.computed(function () {
      return this.firstName() + &quot; &quot; + this.lastName();
    },this);
};
ko.applyBindings(new User(&quot;Nadeem&quot;,&quot;Khedr&quot;), $(&quot;#section1&quot;).get(0));
ko.applyBindings(new User(&quot;Phil&quot;,&quot;Joe&quot;), $(&quot;#section2&quot;).get(0));
</pre>
<h1>Bind a <em>view model</em> to the whole page and bind other <em>view models</em> to sections inside the page</h1>
<p>In a more advanced scenario what we could want is to bind a<em> view model</em> to the whole page &amp; sort of mini <em>view models</em> to different reusable components inside the page</p>
<p>In the previous example we cant define two <em>html</em> sections inside each other with different <em>view models</em>, they must be distinct, in another word we can&#8217;t define a master view model for all the page and a small view model for a part of that page because they will collide</p>
<h3>A scenario that we would want exactly that</h3>
<p>We want a <em>master view model</em> to our page (Layout)<br />
We want a <em>reusable view model</em> for a sidebar that we could use in multiple pages (Partial View)</p>
<p>To achieve that what we will do is go to the parent of the sidebar and tell it stop binding the page <em>view model</em> to your descendant elements</p>
<p>so what will happen exactly is we will define a <em>view model</em> to the whole page without specifying a <em>DOM</em> element to attach it to, and another <em>view model</em> (maybe in another file) for only the side bar and bind it to it</p>
<h3>How to do that without getting errors that the properties in the sidebar doesn&#8217;t exists in the application <em>view model</em></h3>
<p>We will put a custom attribute on the sidebar container, the attribute will look like this</p>
<pre class="brush: xml; title: ; notranslate">
&lt;div id=&quot;sidebarCont&quot; data-bind=&quot;allowBinding: false&quot;&gt;</pre>
<p>what this will do is tell the current view model attached to the document to stop binding itself to the descendant elements for the <em>sidebarCont</em></p>
<p>the <em>allowBinding</em> is a custom <em>bindingHandler</em> that we defined and looks like this</p>
<pre class="brush: jscript; title: ; notranslate">
ko.bindingHandlers.allowBindings = {
      init: function(elem, valueAccessor) {
      var shouldAllowBindings;
      shouldAllowBindings = ko.utils.unwrapObservable(valueAccessor());
      return {
        controlsDescendantBindings: !shouldAllowBindings
      };
    }
  };
</pre>
<p>the above code is self explanatory all the magic happens with the <em><a href="http://knockoutjs.com/documentation/custom-bindings-controlling-descendant-bindings.html">controlsDescendantBindings</a></em><br />
<em><span style="color:#999999;"> if you want to read more about bindingHandlers you can check this</span> <a href="http://knockoutjs.com/documentation/custom-bindings.html">link</a></em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nadeemkhedr.wordpress.com/106/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nadeemkhedr.wordpress.com/106/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nadeemkhedr.wordpress.com&#038;blog=36720970&#038;post=106&#038;subd=nadeemkhedr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nadeemkhedr.wordpress.com/2013/01/29/knockout-view-model-binding-variations-to-a-page/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cb9c077b46a06bf0083e38fc7bc3d16a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nadeemkhedr</media:title>
		</media:content>
	</item>
		<item>
		<title>How the unobtrusive jQuery validate plugin works internally in Asp.net MVC</title>
		<link>http://nadeemkhedr.wordpress.com/2012/08/27/how-the-unobtrusive-jquery-validate-plugin-works-internally-in-asp-net-mvc/</link>
		<comments>http://nadeemkhedr.wordpress.com/2012/08/27/how-the-unobtrusive-jquery-validate-plugin-works-internally-in-asp-net-mvc/#comments</comments>
		<pubDate>Mon, 27 Aug 2012 15:50:53 +0000</pubDate>
		<dc:creator>Nadeem</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[asp.net-mvc]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jquery.validate]]></category>
		<category><![CDATA[unobtrusive-validation]]></category>

		<guid isPermaLink="false">http://nadeemkhedr.wordpress.com/?p=74</guid>
		<description><![CDATA[this is part of &#8220;understanding Asp.net Mvc Unobtrusive Validation&#8221; series How the jQuery validate plugin works internally Understand the Html generated by the unobtrusive validation in Asp.net MVC How the unobtrusive jQuery validate plugin works internally in Asp.net MVC What we will be talking about in this article The parse method parseElement section skipAttach parameter [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nadeemkhedr.wordpress.com&#038;blog=36720970&#038;post=74&#038;subd=nadeemkhedr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>this is part of &#8220;<strong><em>understanding Asp.net Mvc Unobtrusive Validatio</em>n</strong>&#8221; series</p>
<ol>
<li><a href="/2012/08/12/how-the-jquery-validate-plugin-works-internally">How the jQuery validate plugin works internally</a></li>
<li><a href="/2012/08/22/understand-the-html-generated-by-the-unobtrusive-validation-in-asp-net-mvc">Understand the Html generated by the unobtrusive validation in Asp.net MVC</a></li>
<li><span style="text-decoration:underline;">How the unobtrusive jQuery validate plugin works internally in Asp.net MVC</span></li>
</ol>
<p>What we will be talking about in this article</p>
<ul>
<li><a href="#goParse">The <em>parse</em> method</a>
<ul>
<li><a href="#goParseElementSec"><em>parseElement</em> section</a>
<ul>
<li><a href="#goSkipAttach"><em>skipAttach </em>parameter explanation</a></li>
<li><a href="#goParseElement"><em>parseElement</em> function explanation</a></li>
</ul>
</li>
<li><a href="#goValidateInfoSec"><em>validateInfo</em> section</a>
<ul>
<li><a href="#goValidateInfoExp"><em>validateInfo </em> function explanation</a></li>
<li><a href="#goValidationInfoReturn">The return object explanation</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#goAdapters">Adapters</a></li>
</ul>
<p><span id="more-74"></span></p>
<h1 id="goParse">The <em>parse</em> method</h1>
<p>we will explain the cycle of whats happening in the unobtrusive validation at the document load and will understand what is the role of every component</p>
<p>if we look at the end of the <em>jquery.validate.unobtrusive.js</em> we will find</p>
<pre class="brush: jscript; title: ; notranslate">
$(function () {
  $jQval.unobtrusive.parse(document);
});
</pre>
<p>so we called the <em><span style="color:#993300;">parse()</span></em> method and pass it <em><span style="color:#993300;">document</span></em></p>
<p>so whats the parse method exactly</p>
<pre class="brush: jscript; title: ; notranslate">
{
parse: function (selector) {
///
&lt;summary&gt;
/// Parses all the HTML elements in the specified selector. It looks for input elements decorated
/// with the [data-val=true] attribute value and enables validation according to the data-val-*
/// attribute values.
/// &lt;/summary&gt;
///Any valid jQuery selector.

$(selector).find(&quot;:input[data-val=true]&quot;).each(function () {
  $jQval.unobtrusive.parseElement(this, true);
});

var $forms = $(selector)
    .parents(&quot;form&quot;)
    .andSelf()
      .add($(selector).find(&quot;form&quot;))
      .filter(&quot;form&quot;);

$forms.each(function () {
  var info = validationInfo(this);
  if (info) {
    info.attachValidation();
  }
});
}
}
</pre>
<p>There is two sections in the parse method</p>
<h2 id="goParseElementSec">1- <em>parseElement</em> section</h2>
<p><span style="color:#993300;">parseElement</span>(<em>element</em>, <em>skipAttach</em>)</p>
<pre class="brush: jscript; title: ; notranslate">
$(selector).find(&quot;:input[data-val=true]&quot;).each(function () {
  $jQval.unobtrusive.parseElement(this, true);
});
</pre>
<p>so the first thing that happens we iterate over all the elements that have a data-val=true inside the selector that we passed <em>(its document in our case)</em></p>
<p>then call <em>parseElement()</em> and pass it the element we want to validate and <em><span style="color:#008000;">true</span> </em>for <em>skipAttach</em></p>
<ul>
<li>
<h3 id="goSkipAttach"><em><span style="color:#993300;">skipAttach</span> </em>parameter explanation</h3>
<p>a question could come up why we passed <em><span style="color:#008000;">true </span></em>to <em>skipAttach </em>not <em><span style="color:#008000;">false</span></em></p>
<p><em>skipAttach </em>is a flag for calling <em><span style="color:#993300;">validate()</span></em> on the form</p>
<p>If we passed <em><span style="color:#008000;">false</span> </em>it will translate the rules on the element that we have passed then immediately call validate on the rules array and pass along other options used by the unobtrusive validation. <em>(if there is still other element to be parsed they wont)</em></p>
<p>We don&#8217;t want that. We first want to translate all the rules on every element in the form then after all the rules are translated we will call <em>validate()</em> which is basically the second part of the parse method</p>
<p>So what other scenarios we would pass <em><span style="color:#008000;">true</span></em> to <em>skipAttach</em> ?</p>
<p>If we want to add dynamic element to an already validated form we will pass true to skip validating the form again cause to wont make any effect <em>(we will talk about dynamic validating element in the next article)</em></li>
<li>
<h3 id="goParseElement"><em><span style="color:#993300;">parseElement</span> </em>function explanation</h3>
<p>The <em>parseElement</em>() does mainly two things</p>
<ol>
<li>On the first call on an element in a form <em>(No element was called before it in the same form)</em><br />
it will construct an object of options that will be passed to the validate() method, the options are used by the<em> jquery.unobtrusive</em> like a custom <em><span style="color:#993300;">errorPlacement</span></em> function, custom <em><span style="color:#993300;">errorClass </span></em>and an empty rules array <em>(Note: what is responsible of doing all that is a private method called <span style="color:#993300;">validationInfo</span>(form) that is called within <span style="color:#993300;">parseElement</span> and when its called more than 1 time it will just return the same object so we can add, modify or call data/functions in it)</em></li>
<li>For every element when we call <em><span style="color:#993300;">parseElement </span></em>it will understand the rules that are written on this element <em>(the data-*)</em> using the <strong>adapters</strong> <em>(Will explain later how the adapters works)</em>and then translate and add them to the rules array that was constructed in the first call<br />
(<em>Note: every call to <em><span style="color:#993300;">parseElement</span> </em>its result will be saved on the form itself using $.data(&#8220;<span style="color:#993300;">unobtrusiveValidation</span>&#8220;) that&#8217;s how the separate calls sync in the same data source</em>)</li>
</ol>
</li>
</ul>
<h2 id="goValidateInfoSec">2- <em>validateInfo</em> section</h2>
<pre class="brush: jscript; title: ; notranslate">
var $forms = $(selector)
  .parents(&quot;form&quot;)
  .andSelf()
  .add($(selector).find(&quot;form&quot;))
  .filter(&quot;form&quot;);

$forms.each(function () {
  var info = validationInfo(this);
  if (info) {
    info.attachValidation();
  }
});
</pre>
<ul>
<li>
<h3 id="goValidateInfoExp"><em><span style="color:#993300;">validateInfo</span></em> function explanation</h3>
<p>we already said calling <em>validateInfo()</em> will construct an object of options for the <em>validate()</em> method, the options are used by the<em> jquery.unobtrusive</em> like a custom <span style="color:#993300;"><em>errorPlacement</em></span> function, custom <em><span style="color:#993300;">errorClass</span> </em>and an empty rules array</p>
<p>here we also called <em><span style="color:#993300;">validationInfo()</span></em> for every form in the page<br />
basically at this point calling <em><span style="color:#993300;">validationInfo()</span> </em>we will only get the object stored on the form that was already populated in the first phase so we are using it as a getter</p>
<p>then we are calling <em><span style="color:#993300;">attachValidation()</span></em> which is basically calling the <em><span style="color:#993300;">validate()</span></em> method passing it all the options populated by the <em><span style="color:#993300;">validationInfo()</span></em></p>
<pre class="brush: jscript; title: ; notranslate">
data_validation = &quot;unobtrusiveValidation&quot;;

function validationInfo(form) {
  var $form = $(form),
       result = $form.data(data_validation),
       onResetProxy = $.proxy(onReset, form);

  if (!result) {
    result = {
      options: {  // options structure passed to jQuery Validate's validate() method
        errorClass: &quot;input-validation-error&quot;,
        errorElement: &quot;span&quot;,
        errorPlacement: $.proxy(onError, form),
        invalidHandler: $.proxy(onErrors, form),
        messages: {},
        rules: {},
        success: $.proxy(onSuccess, form)
      },
      attachValidation: function () {
        $form
          .unbind(&quot;reset.&quot; + data_validation, onResetProxy)
          .bind(&quot;reset.&quot; + data_validation, onResetProxy)
          .validate(this.options);
        },
      validate: function () {  // a validation function that is called by unobtrusive Ajax
        $form.validate();
        return $form.valid();
      }
    };
    $form.data(data_validation, result);
  }
  return result;
}
</pre>
<p>first we are checking if we already called this function on the form before by using <em>$form.data(&#8220;<span style="color:#993300;">unobtrusiveValidation</span>&#8220;)</em> if we did then do nothing and return the result</li>
<li>
<h3 id="goValidationInfoReturn">The return object explanation</h3>
<p>If its the first time we call <em><span style="color:#993300;">validationInfo()</span></em> then we construct a result object and will save it on the form using <em><span style="color:#993300;">$.data()</span></em> method this object will contain 3 parts:</p>
<ul>
<li>An object which is the basically all the options that we will pass to the <em><span style="color:#993300;">validate()</span></em> method with an empty rules &amp; messages arrays that will be constructed later</li>
<li><em><span style="color:#993300;">attachValidation()</span></em> method will bind a custom event to the form itself &#8220;<span style="color:#993300;"><em>reset.unobtrusiveValidation</em></span>&#8221; and after call validate on the method with all the options , this method will be called when the rules &amp; messages arrays are completed  ( triggering the custom &#8220;<span style="color:#993300;"><em>reset</em></span>&#8221; event will call <em><span style="color:#993300;">onReset() </span></em>method which will basically resets everything )
<pre class="brush: jscript; title: ; notranslate">
function onReset(event) {  // 'this' is the form element
  var $form = $(this);

  $form.data(&quot;validator&quot;).resetForm();
  $form.find(&quot;.control-group&quot;).removeClass(&quot;error&quot;);
  $form.find(&quot;.validation-summary-errors&quot;)
    .addClass(&quot;validation-summary-valid&quot;)
    .removeClass(&quot;validation-summary-errors&quot;);
  $form.find(&quot;.field-validation-error&quot;)
    .addClass(&quot;field-validation-valid&quot;)
    .removeClass(&quot;field-validation-error&quot;)
    .removeData(&quot;unobtrusiveContainer&quot;)
      .find(&quot;&gt;*&quot;)  // If we were using valmsg-replace, get the underlying error
      .removeData(&quot;unobtrusiveContainer&quot;);
}
</pre>
<p>so if we want to trigger the reset event to reset the form</p>
<pre class="brush: jscript; title: ; notranslate">
$('form').trigger('reset.unobtrusiveValidation')
</pre>
</li>
<li>a custom <em><span style="color:#993300;">validate()</span></em> method that will be called from unobtrusive ajax</li>
</ul>
</li>
</ul>
<h1 id="goAdapters">Adapters</h1>
<p>I intentionally left the <em>adapters</em> section out when i talked about the <em><span style="color:#993300;">parseElement()</span> </em>method because its complicated enough to be in a sub-section</p>
<p>We looked at how Html is generated using unobtrusive validation and how to add custom validation attribute in normal <em>jquery.validate what links between the two is the <strong>Adapters</strong><br />
</em></p>
<p><strong>So What is the adapter&#8217;s responsibility ?</strong></p>
<p>it is responsible for translating the Html data-* to a format that can be understood by the normal <em>jquery.validate</em></p>
<p>If a user want to add a custom validation method using the unobtrusive validation he must also provide an adapter for it</p>
<p>the <em>adapters</em> collection resides in <em><span style="color:#993300;">$.validator.unobtrusive.adapters</span> </em></p>
<ul>
<li>the adapters collection consist of all the default adapters defined by default in <em>jquery.unobstrusive</em> and the ones that the user has defined</li>
<li>It also contains 4 methods for adding custom adapters that we will take a look at later</li>
</ul>
<p><a href="http://nadeemkhedr.files.wordpress.com/2012/08/adapters.png"><img class="alignnone size-full wp-image-86" title="Adapters" alt="" src="http://nadeemkhedr.files.wordpress.com/2012/08/adapters.png?w=645&#038;h=252" width="645" height="252" /></a></p>
<p>so lets look at the most generic method which is</p>
<p><em>jQuery.validator.unobtrusive.adapters.add(<span style="color:#993300;">adapterName</span>, <span style="color:#993300;">[params]</span>, <span style="color:#993300;">fn</span>)</em></p>
<p>you can consider this method the <em>$.ajax</em> method and the other three are helper methods that uses it</p>
<p>so lets explain the parameters</p>
<ul>
<li><em><strong>adapterName:</strong></em> is the adapter name as the name implies , and it matches the <em>ruleName</em> in the Html element <em>(data-val-ruleName)</em></li>
<li><em><strong>[params]:</strong></em> an optional parameter array that the validation method would use to complete validation</li>
<li><strong><em>fn</em>: </strong>Is called to map the Html <em>data-*</em>to rules and messages used by the validate() method and it has a parameter option passed to it which is an object containing the following properties:
<ul>
<li><em><strong>element:</strong></em> the Html element being validated</li>
<li><em><strong>form</strong></em>: the form element</li>
<li><em><strong>message:</strong></em> the error message for this rule extracted from <em>data-*</em> attribute on the element</li>
<li><em><strong>params:</strong></em> parameters that are used for the validation and its an array extracted from the <em>data-*</em> attributes on the Html element <em>(data-val-ruleName-param1)</em></li>
<li><em><strong>rules:</strong></em> The jquery rules array for this element , your expected to add to this array the rule(s) that this adapter is used for<br />
you will pass key/value pairs , the key is the validation rule name , the value is the parameters used for this rule <em>(check this <a href="/2012/08/12/how-the-jquery-validate-plugin-works-internally/#goCustomRulesAdd">section</a> in that article for adding custom rules to jquery.validate)</em></li>
<li><em><strong>messages:</strong></em> The jquery messages array for this element, same as the rules object you are expected to fill it and its used as the messages object for this Html element in the validate method</li>
</ul>
<p>Note: There is no return result from the method. Whats happening manipulating the rules &amp; messages arrays will directly be saved on the form itself using<em> $.data(&#8220;<span style="color:#993300;">unobtrusiveValidation</span>&#8220;)</em> you can check the <a href="#goParseElementSec"><em>parseElement</em></a> method for the details of how the parameter where passed to the adapter function</li>
</ul>
<p>Example:</p>
<p><strong>Html</strong></p>
<pre class="brush: xml; title: ; notranslate">
&lt;input id=&quot;val&quot; type=&quot;text&quot; name=&quot;val&quot; data-val=&quot;true&quot; data-val-between=&quot;Must be in the right range&quot; data-val-between-min=&quot;5&quot; data-val-between-max=&quot;30&quot; /&gt;
</pre>
<p><strong>Javascript</strong></p>
<pre class="brush: jscript; title: ; notranslate">
//The adapter
jQuery.validator.unobtrusive.adapters.add(
  'between', ['min' ,'max'], function (options) {
    options.rules['between'] =  {
      min: options.params.min,
      max: options.params.max
    };
    options.messages['between'] = options.message;
  }
);

//The validation method
jQuery.validator.addMethod(&quot;between&quot;, function (value, element, params) {
  params.min == 5; //true
  params.max == 30; //true
});
</pre>
<p>so what about the other adapters</p>
<ul>
<li><em> addBool</em></li>
<li><em>addSingleVal</em></li>
<li><em>addMinMax</em></li>
</ul>
<p>They are all pretty simple if you understood the concept of adding a custom adapter using the <em><span style="color:#993300;">add()</span></em> method explained before</p>
<p>You can check Brad Wilson&#8217;s <a href="http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html">article</a> he explained in it the adapters in depth</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nadeemkhedr.wordpress.com/74/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nadeemkhedr.wordpress.com/74/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nadeemkhedr.wordpress.com&#038;blog=36720970&#038;post=74&#038;subd=nadeemkhedr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nadeemkhedr.wordpress.com/2012/08/27/how-the-unobtrusive-jquery-validate-plugin-works-internally-in-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cb9c077b46a06bf0083e38fc7bc3d16a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nadeemkhedr</media:title>
		</media:content>

		<media:content url="http://nadeemkhedr.files.wordpress.com/2012/08/adapters.png" medium="image">
			<media:title type="html">Adapters</media:title>
		</media:content>
	</item>
		<item>
		<title>Understand the Html generated by the unobtrusive validation in Asp.net MVC</title>
		<link>http://nadeemkhedr.wordpress.com/2012/08/22/understand-the-html-generated-by-the-unobtrusive-validation-in-asp-net-mvc/</link>
		<comments>http://nadeemkhedr.wordpress.com/2012/08/22/understand-the-html-generated-by-the-unobtrusive-validation-in-asp-net-mvc/#comments</comments>
		<pubDate>Wed, 22 Aug 2012 13:37:51 +0000</pubDate>
		<dc:creator>Nadeem</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[asp.net-mvc]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jquery.validate]]></category>
		<category><![CDATA[unobtrusive-validation]]></category>

		<guid isPermaLink="false">http://nadeemkhedr.wordpress.com/?p=60</guid>
		<description><![CDATA[this is part of &#8220;understanding Asp.net Mvc Unobtrusive Validation&#8221; series How the jQuery validate plugin works internally Understand the Html generated by the unobtrusive validation in Asp.net MVC How the unobtrusive jQuery validate plugin works internally in Asp.net MVC What we will be talking about in this article The idea of unobtrusive JavaScript Difference between [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nadeemkhedr.wordpress.com&#038;blog=36720970&#038;post=60&#038;subd=nadeemkhedr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>this is part of &#8220;<strong><em>understanding Asp.net Mvc Unobtrusive Validatio</em>n</strong>&#8221; series</p>
<ol>
<li><a href="/2012/08/12/how-the-jquery-validate-plugin-works-internally">How the jQuery validate plugin works internally</a></li>
<li><span style="text-decoration:underline;">Understand the Html generated by the unobtrusive validation in Asp.net MVC</span></li>
<li><a href="/2012/08/27/how-the-unobtrusive-jquery-validate-plugin-works-internally-in-asp-net-mvc">How the unobtrusive jQuery validate plugin works internally in Asp.net MVC</a></li>
</ol>
<p>What we will be talking about in this article</p>
<ul>
<li><a href="#goIntro">The idea of unobtrusive JavaScript</a></li>
<li><a href="#goNorAndUnob">Difference between normal and unobtrusive validation</a></li>
<li><a href="#goUnderstandUnob">Understanding Unobtrusive validation</a>
<ul>
<li><a href="#goInputsAndValidation">Inputs and their validation rules and how they work</a></li>
<li><a href="#goValidationMessages">The validation messages and how they work in the unobtrusive validation</a></li>
</ul>
</li>
</ul>
<p><span id="more-60"></span></p>
<h1 id="goIntro">The idea of unobtrusive JavaScript</h1>
<p>Microsoft released its validation module from the first version of Mvc but it has really matured in every version until finally the release of unobtrusive validation in Asp.net Mvc 3</p>
<p>In short even writing modern JavaScript, which is basically JavaScript in a separate js file. we sometimes need data associated with the Html so we write some metadata JavaScript objects inside the Html page itself and will call a function from the external js file passing it the metadata object in the page</p>
<p>one of the goals of unobtrusive JavaScript is to separate JavaScript from Html markup</p>
<p>To read more about this subject check <a href="http://en.wikipedia.org/wiki/Unobtrusive_JavaScript">this article</a></p>
<hr />
<h1 id="goNorAndUnob">Difference between normal and unobtrusive validation</h1>
<p>We now will see a Model and the corresponding Html generated using MVC 2 and MVC 3 using unobtrusive validation</p>
<p><strong>Our Model</strong></p>
<pre class="brush: csharp; title: ; notranslate">
public class ValidationModel {
  [Required]
  public string FirstName { get; set; }

  [Required, StringLength(60)]
  public string LastName { get; set; }

  [Range(1, 130)]
  public int Age { get; set; }
}
</pre>
<p><strong>The View in MVC 2 using html helpers</strong></p>
<pre class="brush: xml; title: ; notranslate">
&lt;label for=&quot;FirstName&quot;&gt;FirstName&lt;/label&gt;
&lt;input id=&quot;FirstName&quot; class=&quot;text-box single-line&quot; type=&quot;text&quot; name=&quot;FirstName&quot; value=&quot;&quot; /&gt;
&lt;span id=&quot;FirstName_validationMessage&quot; class=&quot;field-validation-valid&quot;&gt;&lt;/span&gt;

&lt;label for=&quot;LastName&quot;&gt;LastName&lt;/label&gt;
&lt;input id=&quot;LastName&quot; class=&quot;text-box single-line&quot; type=&quot;text&quot; name=&quot;LastName&quot; value=&quot;&quot; /&gt;
&lt;span id=&quot;LastName_validationMessage&quot; class=&quot;field-validation-valid&quot;&gt;&lt;/span&gt;

&lt;label for=&quot;Age&quot;&gt;Age&lt;/label&gt;
&lt;input id=&quot;Age&quot; class=&quot;text-box single-line&quot; type=&quot;text&quot; name=&quot;Age&quot; value=&quot;&quot; /&gt;
&lt;span id=&quot;Age_validationMessage&quot; class=&quot;field-validation-valid&quot;&gt;&lt;/span&gt;

&lt;script type=&quot;text/javascript&quot;&gt;// &lt;![CDATA[
if (!window.mvcClientValidationMetadata) { window.mvcClientValidationMetadata = []; } window.mvcClientValidationMetadata.push({&quot;Fields&quot;:[{&quot;FieldName&quot;:&quot;FirstName&quot;,&quot;ReplaceValidationMessageContents&quot;:true,&quot;ValidationMessageId&quot;:&quot;FirstName_validationMessage&quot;,&quot;ValidationRules&quot;:[{&quot;ErrorMessage&quot;:&quot;The FirstName field is required.&quot;,&quot;ValidationParameters&quot;:{},&quot;ValidationType&quot;:&quot;required&quot;}]},{&quot;FieldName&quot;:&quot;LastName&quot;,&quot;ReplaceValidationMessageContents&quot;:true,&quot;ValidationMessageId&quot;:&quot;LastName_validationMessage&quot;,&quot;ValidationRules&quot;:[{&quot;ErrorMessage&quot;:&quot;The LastName field is required.&quot;,&quot;ValidationParameters&quot;:{},&quot;ValidationType&quot;:&quot;required&quot;},{&quot;ErrorMessage&quot;:&quot;The field LastName must be a string with a maximum length of 60.&quot;,&quot;ValidationParameters&quot;:{&quot;max&quot;:60},&quot;ValidationType&quot;:&quot;length&quot;}]},{&quot;FieldName&quot;:&quot;Age&quot;,&quot;ReplaceValidationMessageContents&quot;:true,&quot;ValidationMessageId&quot;:&quot;Age_validationMessage&quot;,&quot;ValidationRules&quot;:[{&quot;ErrorMessage&quot;:&quot;The field Age must be between 1 and 130.&quot;,&quot;ValidationParameters&quot;:{&quot;min&quot;:1,&quot;max&quot;:130},&quot;ValidationType&quot;:&quot;range&quot;},{&quot;ErrorMessage&quot;:&quot;The Age field is required.&quot;,&quot;ValidationParameters&quot;:{},&quot;ValidationType&quot;:&quot;required&quot;},{&quot;ErrorMessage&quot;:&quot;The field Age must be a number.&quot;,&quot;ValidationParameters&quot;:{},&quot;ValidationType&quot;:&quot;number&quot;}]}],&quot;FormId&quot;:&quot;form0&quot;,&quot;ReplaceValidationSummary&quot;:true,&quot;ValidationSummaryId&quot;:&quot;validationSummary&quot;});
// ]]&gt;&lt;/script&gt;
</pre>
<p><strong>The View in MVC 3 using html helpers &amp; unobtrusive validation</strong></p>
<pre class="brush: xml; title: ; notranslate">
&lt;label for=&quot;FirstName&quot;&gt;FirstName&lt;/label&gt;
&lt;input id=&quot;FirstName&quot; class=&quot;text-box single-line&quot; type=&quot;text&quot; name=&quot;FirstName&quot; value=&quot;&quot; data-val=&quot;true&quot; data-val-required=&quot;The FirstName field is required.&quot; /&gt;

&lt;label for=&quot;LastName&quot;&gt;LastName&lt;/label&gt;
&lt;input id=&quot;LastName&quot; class=&quot;text-box single-line&quot; type=&quot;text&quot; name=&quot;LastName&quot; value=&quot;&quot; data-val=&quot;true&quot; data-val-length=&quot;The field LastName must be a string with a maximum length of 60.&quot; data-val-length-max=&quot;60&quot; data-val-required=&quot;The LastName field is required.&quot; /&gt;

&lt;label for=&quot;Age&quot;&gt;Age&lt;/label&gt;
&lt;input id=&quot;Age&quot; class=&quot;text-box single-line&quot; type=&quot;text&quot; name=&quot;Age&quot; value=&quot;&quot; data-val=&quot;true&quot; data-val-number=&quot;The field Age must be a number.&quot; data-val-range=&quot;The field Age must be between 1 and 130.&quot; data-val-range-max=&quot;130&quot; data-val-range-min=&quot;1&quot; data-val-required=&quot;The Age field is required.&quot; /&gt;

</pre>
<p><em>this code was taken from Brad Wilson <a href="http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html">article</a></em></p>
<p>As we can see the Html inputs generated from MVC 2 don&#8217;t have any knowledge about what kind of validation rules that are applied to them.<br />
There is only a big JavaScript object containing all the info of the validation applied to every element on this page</p>
<p>On the other hand if we look at the inputs generated with MVC 3 it looks like they have much more metadata info in them and this is all the info needed for validating these fields in a from of <em>data-*</em> attributes and there is no need for a big JavaScript object</p>
<pre class="brush: xml; title: ; notranslate">
&lt;!-- Input generated using MVC2 --&gt;
&lt;input id=&quot;FirstName&quot; class=&quot;text-box single-line&quot; type=&quot;text&quot; name=&quot;FirstName&quot; value=&quot;&quot; /&gt;

&lt;!-- Input generated using MVC3 --&gt;
&lt;input id=&quot;FirstName&quot; class=&quot;text-box single-line&quot; type=&quot;text&quot; name=&quot;FirstName&quot; value=&quot;&quot; data-val=&quot;true&quot; data-val-required=&quot;The FirstName field is required.&quot; /&gt;
</pre>
<hr />
<h1 id="goUnderstandUnob">Understanding Unobtrusive validation</h1>
<h2 id="goInputsAndValidation">1-Inputs and their validation rules and how they work</h2>
<p>so lets explain what happens with these <em>data-*</em> attributes</p>
<ul>
<li>MVC outputs the <em>data-*</em> attributes based on the validation rules</li>
<li><em>jquery.validate.unobtrusive</em> will read these rules and translate them in a way</li>
<li>after the unobtrusive validation translates these rules it will call <em><span style="color:#993300;">validate()</span></em> method and pass the rules array with other options to validate it</li>
</ul>
<p>there are three parts of any unobtrusive rule in any Html element</p>
<ul>
<li>The <em>data-val=&#8221;true&#8221;</em> its just a flag that this element has unobtrusive validation attached to it</li>
<li>The <em>data-val-rulename=&#8221;message&#8221;</em> it does two things first it declares that this element has a rule which is the <em>data-val-rulename</em> and the other is the error message which is the value of it</li>
<li>The <em>data-val-rulename-additionalvalues=&#8221;value&#8221;</em> this for adding additional values required by the validation rule to complete its validation <em>(Ex. a range validation that must be more than a value and less than a value)</em></li>
</ul>
<p>we can take a closer look at a generated input and explain these <em>data-*</em> attributes</p>
<pre class="brush: xml; title: ; notranslate">
&lt;input id=&quot;Name&quot; class=&quot;ignore&quot; type=&quot;text&quot; name=&quot;Name&quot; value=&quot;&quot; data-val=&quot;true&quot; data-val-required=&quot;*&quot; data-val-atleastonerequired=&quot;Enter at least Name, Email or Lastname&quot; data-val-atleastonerequired-attributes=&quot;Email,LName&quot; /&gt;
</pre>
<p>there are two rules attached to this element<br />
one is the built in <em>required</em> attribute and the other is a custom one called <em>atleastonerequired</em><br />
and when the user doesn&#8217;t enter any data and press submit a <em>*</em> will appear as the validation message indicating the element is required and if the user violated the <em>atleastonerequired</em> its validation message would appear instead</p>
<h2 id="goValidationMessages">2-The validation messages and how they work in the unobtrusive validation</h2>
<p>Lets start with an example and build from there</p>
<pre class="brush: xml; title: ; notranslate">
&lt;!-- Required input using unobtrusive validation --&gt;
&lt;input id=&quot;FirstName&quot; class=&quot;text-box single-line&quot; type=&quot;text&quot; name=&quot;FirstName&quot; value=&quot;&quot; data-val=&quot;true&quot; data-val-required=&quot;The FirstName field is required.&quot; /&gt;

&lt;!-- The input's validation message placeholder --&gt;
&lt;span data-valmsg-replace=&quot;true&quot; data-valmsg-for=&quot;Name&quot; class=&quot;field-validation-valid help-inline&quot; /&gt;
</pre>
<p>As we can see there are two <em>data-*</em> on the validation placeholder</p>
<ul>
<li><em><span style="color:#993300;">&#8220;data-valmsg-for&#8221; </span></em> its value is the input&#8217;s name attribute that this placeholder belongs to , the input &amp; placeholder must be in the same form tag</li>
<li><em><span style="color:#993300;">&#8220;data-valmsg-replace&#8221; </span></em> its <em><span style="color:#993300;">true</span> </em>by default the difference between true and false , true will change the text of the placeholder depending on what validation rule was violated if its false it will be static and the content won&#8217;t change only the class name will switch on valid and invalid</li>
</ul>
<p>if there is violation of any of the rules there will be a class name of <em><span style="color:#993300;">&#8220;field-validation-error&#8221;</span> </em>and if there is none the class name will be <em><span style="color:#993300;">&#8220;field-validation-valid&#8221;</span></em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nadeemkhedr.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nadeemkhedr.wordpress.com/60/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nadeemkhedr.wordpress.com&#038;blog=36720970&#038;post=60&#038;subd=nadeemkhedr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nadeemkhedr.wordpress.com/2012/08/22/understand-the-html-generated-by-the-unobtrusive-validation-in-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cb9c077b46a06bf0083e38fc7bc3d16a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nadeemkhedr</media:title>
		</media:content>
	</item>
		<item>
		<title>How the jQuery validate plugin works internally</title>
		<link>http://nadeemkhedr.wordpress.com/2012/08/12/how-the-jquery-validate-plugin-works-internally/</link>
		<comments>http://nadeemkhedr.wordpress.com/2012/08/12/how-the-jquery-validate-plugin-works-internally/#comments</comments>
		<pubDate>Sun, 12 Aug 2012 12:23:05 +0000</pubDate>
		<dc:creator>Nadeem</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[asp.net-mvc]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jquery.validate]]></category>
		<category><![CDATA[unobtrusive-validation]]></category>

		<guid isPermaLink="false">http://nadeemkhedr.wordpress.com/?p=8</guid>
		<description><![CDATA[There are plenty of articles that target how to write custom rules to the jquery.validate plugin but very few targets how this plugin internally works and that&#8217;s what we will discuss in this article this is part of &#8220;understanding Asp.net Mvc Unobtrusive Validation&#8221; series How the jQuery validate plugin works internally Understand the Html generated [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nadeemkhedr.wordpress.com&#038;blog=36720970&#038;post=8&#038;subd=nadeemkhedr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>There are plenty of articles that target how to write custom rules to the jquery.validate plugin but very few targets how this plugin internally works and that&#8217;s what we will discuss in this article</p>
<p>this is part of &#8220;<strong><em>understanding Asp.net Mvc Unobtrusive Validatio</em>n</strong>&#8221; series</p>
<ol>
<li><span style="text-decoration:underline;">How the jQuery validate plugin works internally</span></li>
<li><a href="/2012/08/22/understand-the-html-generated-by-the-unobtrusive-validation-in-asp-net-mvc">Understand the Html generated by the unobtrusive validation in Asp.net MVC</a></li>
<li><a href="/2012/08/27/how-the-unobtrusive-jquery-validate-plugin-works-internally-in-asp-net-mvc">How the unobtrusive jQuery validate plugin works internally in Asp.net MVC</a>
</li>
</ol>
<p>What we will be talking about in this article</p>
<ul>
<li><a href="#goValidateForm">How to validate a form</a></li>
<li><a href="#goMessages">The validation messages and how they work</a></li>
<li><a href="#goCustomRulesAdd">Add custom validation rules.</a></li>
<li><a href="#goCallValidate">What exactly happens when we call the validate method</a></li>
</ul>
<p><span id="more-8"></span></p>
<h1 id="goValidateForm">How to validate a form ?</h1>
<p>There are basically 2 ways to validate your form</p>
<h2>1- Use Class names as rules</h2>
<p>How it works</p>
<p>We decorate the fields that we want to validate with an html <em>class</em> attribute and that is what will trigger the validation</p>
<p>So if we want a textbox to be required we add to that input element a class value of &#8220;<em><span style="color:#800000;">required</span></em>&#8220;</p>
<p><strong>Html</strong></p>
<pre class="brush: xml; title: ; notranslate">
&lt;form action=&quot;/&quot; method=&quot;post&quot;&gt;
  &lt;input id=&quot;Name&quot; type=&quot;text&quot; name=&quot;Name&quot; value=&quot;&quot; /&gt;
  &lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt;
&lt;/form&gt;
</pre>
<p><strong>Javascript</strong></p>
<pre class="brush: jscript; title: ; notranslate">
$(document).ready(function() {
  $('form').validate();
});
</pre>
<p>With this method you can define certain classes with multiple rules</p>
<p>Pros &amp; cons of this approach</p>
<ul>
<li>only works with rules that takes no arguments</li>
<li>we are using the html <em>class</em> attribute for something not related to its original intent which is a break for separation of concerns principle</li>
<li>but still it’s very easy to setup</li>
</ul>
<h2>Using <em>addClassRules</em> method</h2>
<p>Using <em>addClassRules</em> function gives us the ability to use compound rules as a single class</p>
<pre class="brush: jscript; title: ; notranslate">
$.validator.addClassRules({
  name: {
    required: true,
    minlength: 2
  },
  zip: {
    required: true,
    digits: true,
    minlength: 5,
    maxlength: 5
  }
});
</pre>
<p>This will add 2 new class rules, &#8220;<em><span style="color:#993300;">name</span></em>&#8221; and &#8220;<em><span style="color:#993300;">zip</span></em>&#8221; so if we have an input element and gave it a <em>class</em> of &#8220;<em><span style="color:#800000;">zip</span></em>&#8221; it will be required, the user must only insert digits and the length must be exactly 5 characters</p>
<pre class="brush: xml; title: ; notranslate">
&lt;input class=&quot;zip&quot; type=&quot;text&quot; name=&quot;zipCode&quot; /&gt;
</pre>
<p>info: to use a custom message for a specific rule in a compound class rules requires a workaround, you have to alias the rules like &#8220;<em><span style="color:#800000;">required</span></em>&#8221; to a new rule and in the new rule you define a default message</p>
<pre class="brush: jscript; title: ; notranslate">
$.validator.addMethod(&quot;newrequired&quot;, $.validator.methods.required, &quot;new name is required&quot;);
</pre>
<p>or you can use the &#8220;<em><span style="color:#993300;">title</span>&#8220;</em> html attribute and it will be the error message for the compound rule</p>
<p>Note: class names validation only works on the validation rules that doesn&#8217;t accept any arguments</p>
<h2>2- Add rules as JSON object to the validate method</h2>
<p>by the name you should have figured out that the validation method takes a json object, we then could specify the fields that we want to validate and the validation rules for it</p>
<p><strong>Html</strong></p>
<pre class="brush: xml; title: ; notranslate">
&lt;form&gt;
  &lt;input id=&quot;something&quot; type=&quot;text&quot; name=&quot;userEmail&quot; /&gt;
  &lt;input id=&quot;submit&quot; type=&quot;submit&quot; value=&quot;submit&quot; /&gt;
&lt;/form&gt;
</pre>
<p><strong>Javascript</strong></p>
<pre class="brush: jscript; title: ; notranslate">
$('form').validate({
  rules: {
    userEmail: {
      email: true,
      required: true
    }
  }
});
</pre>
<p>note: when you pass the rules object to the validate function the key should be the value of the &#8220;<em><span style="color:#993300;">name</span></em>&#8221; attribute not the value of the &#8220;<em><span style="color:#993300;">id</span></em>&#8221; as you can see in the example the key is &#8220;<em><span style="color:#993300;">userEmail</span></em>&#8221; which is the value of the name attribute and the id is something else</p>
<p>Pros &amp; cons of this approach</p>
<ul>
<li>this approach will give us the ability to use more validation rules that require arguments like <em>minlength</em>, <em>remote</em>, <em>equalTo</em> , etc..</li>
<li>great and manual control over everything</li>
<li>but the user have to make a separate validate function with different options for every form</li>
</ul>
<h2>Adding or removing dynamic rules</h2>
<h4>Adding rules</h4>
<p>To add a rule we should use the <em>rules</em> method on a <em>jquery</em> elements itself after the form is validated and pass the first parameter the string &#8220;<em><span style="color:#993300;">add</span></em>&#8221; and the second one an object of rules you want to add for this element (you can also pass a message object for the rules you added)</p>
<pre class="brush: jscript; title: ; notranslate">
$('.input').rules('add', {
  required: true,
  messages: {
    required: true
  }
})
</pre>
<h4>Removing rules</h4>
<p>if you want to remove a rule or set of rules you pass the string &#8220;<em><span style="color:#993300;">remove</span></em>&#8221; as the first parameter for the rules method then the second will be a string that containing the rules you want to remove separated by a space</p>
<pre class="brush: jscript; title: ; notranslate">
$('.input').rules('remove', 'min max');
</pre>
<h3></h3>
<h3>More manual approach</h3>
<p>accessing the <em>validator</em> object after the form is validated and from it access the <em>rules</em> object and then we can extend or modify it</p>
<pre class="brush: jscript; title: ; notranslate">
var validator = $('form').data('validator');

validator.settings.rules.objectName = {
  required: true
}
</pre>
<p>this approach is very useful if you have an already made rules or messages objects you could extend the rules of the <em>validator</em> with your own</p>
<pre class="brush: jscript; title: ; notranslate">
$.extend(validator.settings, { rules: rules, messages: messages });
</pre>
<p>Note: to understand the <em>validator</em> you can check <a href="#goCallValidate">What exactly happens when we call the <em>validate</em> method</a> section</p>
<hr />
<h1 id="goMessages">The validation messages and how they work.</h1>
<p>There are 3 ways to provide a validation message</p>
<ol>
<ol>
<li>pass a &#8220;<em><span style="color:#993300;">messages</span></em>&#8221; object to the <em>validate</em>method the messages object consist of key/value pairs the key is the name of the element and the value is an object containing every rule and its message
<pre class="brush: jscript; title: ; notranslate">
$('form').validate({
  rules: {
    userEmail: {
    email: true,
    required: true
    }
  },
  messages: {
    userEmail: {
    email: &quot;Please enter your email&quot;,
    required: &quot;*&quot;
    }
  }
});
</pre>
</li>
<li>The value of the &#8220;<em><span style="color:#993300;">title</span></em>&#8221; attribute on the element
<pre class="brush: xml; title: ; notranslate">
&lt;input id=&quot;Email&quot; title=&quot;you have to enter a value&quot; type=&quot;text&quot; name=&quot;Email&quot; /&gt;
</pre>
</li>
<li>default message when defining the validation rule and there are built in default messages for the built in rules</li>
</ol>
</ol>
<p>Note: These 3 ways override each other based on the priority, passing the messages object is the most important and the default message is the least important</p>
<hr />
<h1 id="goCustomRulesAdd">Add custom validation rules.</h1>
<p>When we want to add more validation rules than the default ones we use <em>$.validator.addMethod</em></p>
<p>this method accepts as parameters the following</p>
<ul>
<li>rule name</li>
<li>a function that do the validation</li>
<li>a default message</li>
</ul>
<p>the function that do the validation can be in 2 different signatures</p>
<pre class="brush: jscript; title: ; notranslate">
function validationMethod (value, element)
// OR
function validationMethod (value, element, params)
</pre>
<p>lets explain these parameters</p>
<ul>
<li>value: the value of the DOM element that will be validated</li>
<li>element: the DOM element itself</li>
<li>params : is what you pass as a value to this validation ruleExample what <em>params</em>will equal
<pre class="brush: jscript; title: ; notranslate">
$('form').validate({
  rules: {
    firstname: {
      compare: {
        type: &quot;notequal&quot;,
        otherprop: &quot;lastname&quot;
      }
    }
  }
});
</pre>
<p>in this example the <em>params </em>will equal to</p>
<pre class="brush: jscript; title: ; notranslate">
{type:&quot;notequal&quot;, otherprop: &quot;lastname&quot;}
</pre>
</li>
</ul>
<p>Example to add custom rule</p>
<pre class="brush: jscript; title: ; notranslate">
$.validator.addMethod(&quot;notnumbers&quot;, function(value, element) {
  return !/[0-9]*/.test(value);
},
&quot;Please don't insert numbers.&quot;)
</pre>
<hr />
<h1 id="goCallValidate">What exactly happens when we call the <em>validate</em> method.</h1>
<p>When you call <em>validate</em> on a form mainly couple of things happens behind the scene</p>
<ul>
<li>
<h4>Create a <em>validator </em>object with all the rules and options and attach it to the form.</h4>
<h4>The <em>validate</em> method attaches the <em>validator</em> using <em>$.data</em> , you can get it by selecting the form and calling the <em>jquery $.data</em> function and passing it &#8220;<em><span style="color:#993300;">validator</span></em>&#8220;. The <em>validator</em> object is all the metadata for the validation giving us the ability to access the validate options at anytime in the page cycle</h4>
<h4>using this object you can change at <strong>runtime</strong> the options that you passed to the validate method like adding or removing rules, change what happens when the field is valid or invalid or even provide an ignore selector</h4>
<pre class="brush: jscript; title: ; notranslate">
//getting the validator
var validator = $(&quot;.selector&quot;).data(&quot;validator&quot;)
</pre>
<h4>Note: when you call <em>validate</em> on a form that was already validated it will just return the <em>validator</em> object using also <em>$.data</em> and all the options passed to validate method will be omitted</h4>
<pre class="brush: jscript; title: ; notranslate">
var validator = $(&quot;.selector&quot;).validate(/* rules will be omitted */)
</pre>
</li>
<li>
<h4>subscribe events to the form itself</h4>
<p>What will happens when you click submit and there are invalid elements is you will trigger the validation of the fields, if one of them is not valid then the validate plugin will listen to it more closely to check if it is valid or not</p>
<p>The events that are subscribed to the form are click, focusin, focusout, keyup, submit</p>
<p>note: you can disable these events by passing them as keys to the validate method and false as their value</p>
<pre class="brush: jscript; title: ; notranslate">
$(&quot;.selector&quot;).validate({
  onfocusout: false,
     onkeyup: false,
     onclick: false,
    onsubmit: false
});
</pre>
</li>
</ul>
<p>See also:</p>
<ul>
<li><a title="official jquery.validate options" href="http://docs.jquery.com/Plugins/Validation/validate#toptions">official jQuery.validate options</a></li>
<li><a href="http://khaidoan.wikidot.com/jquery-validation">Q&amp;A on how jQuery.validate works</a></li>
<li><a href="http://docs.jquery.com/Plugins/Validation#List_of_built-in_Validation_methods" target="_blank">List of the built-in validation methods </a></li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nadeemkhedr.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nadeemkhedr.wordpress.com/8/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nadeemkhedr.wordpress.com&#038;blog=36720970&#038;post=8&#038;subd=nadeemkhedr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nadeemkhedr.wordpress.com/2012/08/12/how-the-jquery-validate-plugin-works-internally/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cb9c077b46a06bf0083e38fc7bc3d16a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nadeemkhedr</media:title>
		</media:content>
	</item>
	</channel>
</rss>
