<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>popcyclical - jquery</title>
    <link>http://popcyclical.com/</link>
    <description>The software development blog of James "poprhythm" Kolpack</description>
    <language>en-us</language>
    <copyright>James Kolpack</copyright>
    <lastBuildDate>Sun, 03 Jan 2010 05:47:00 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.12105.0</generator>
    <managingEditor>dasblog@example.com</managingEditor>
    <webMaster>dasblog@example.com</webMaster>
    <item>
      <trackback:ping>http://popcyclical.com/Trackback.aspx?guid=417495f7-1ea9-46dc-a3fe-0829928b7a58</trackback:ping>
      <pingback:server>http://popcyclical.com/pingback.aspx</pingback:server>
      <pingback:target>http://popcyclical.com/PermaLink,guid,417495f7-1ea9-46dc-a3fe-0829928b7a58.aspx</pingback:target>
      <dc:creator>James Kolpack</dc:creator>
      <wfw:comment>http://popcyclical.com/CommentView,guid,417495f7-1ea9-46dc-a3fe-0829928b7a58.aspx</wfw:comment>
      <wfw:commentRss>http://popcyclical.com/SyndicationService.asmx/GetEntryCommentsRss?guid=417495f7-1ea9-46dc-a3fe-0829928b7a58</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
When using <a href="http://www.appelsiini.net/projects/jeditable">Jeditable</a>, there
is no form element to bind <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">jQuery
Validate</a> rules with.  Instead, when an editable element is clicked or activated,
it dynamically creates a new form and input element and destroys them after the user
is done editing.  For the ViewModel from <a href="/2010/01/01/jQueryValidateAndJeditablePart1.aspx">Part
1</a>, the View might be rendered like so for <a href="http://www.appelsiini.net/projects/jeditable">Jeditable</a>:
</p>
        <pre>
          <code>&lt;%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage&lt;ValidateViewModel&gt;"
%&gt; &lt;asp:Content ContentPlaceHolderID="MainContent" runat="server"&gt; &lt;%
using(Html.BeginForm()) {%&gt; &lt;%= Html.ValidationSummary() %&gt; &lt;label for="StringRequired"&gt;StringRequired:&lt;/label&gt;
&lt;div class="editable" id="StringRequired" name="StringRequired"&gt; &lt;%= Model.StringRequired
%&gt; &lt;/div&gt; &lt;label for="DoubleRange13_100"&gt;DoulbeRange13_100:&lt;/label&gt;
&lt;div class="editable" id="DoubleRange13_100" name="DoubleRange13_100"&gt; &lt;%=
Model.DoubleRange13_100%&gt; &lt;/div&gt; &lt;%} %&gt; &lt;/asp:Content&gt;</code>
        </pre>
        <p>
          <a href="http://xval.codeplex.com/">xVal</a>’s <code>ClientSideValidation&lt;TViewModel&gt;()</code> used
in <a href="/2010/01/01/jQueryValidateAndJeditablePart1.aspx">Part 1</a> won’t work
to validate this.  The reason?  It generates a script that binds validation
directly to the form elements on page load.  The rendered script looks for the
ViewModel looks like:
</p>
        <pre>
          <code>&lt;script type="text/javascript"&gt; xVal.AttachValidator(null, {"Fields":[
{ "FieldName":"StringRequired", "FieldRules":[ { "RuleName":"Required", "RuleParameters":{
}, "Message":"This string is required" }, { "FieldName":"DoubleRange13_100", "FieldRules":[
{ "RuleName":"Range", "RuleParameters":{ "Min":"13", "Max":"100", "Type":"decimal"
}, "Message":"Must be between 13 and 100" } ] } ] } ]}, {}) &lt;/script&gt;</code>
        </pre>
        <p>
The rules are in the xVal’s StandardJSON format and the <code>AttachValidator</code> function
(in <code>xVal.jquery.validate.js</code>) scans the DOM and attaches <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">jQuery
Validate</a> rules as attributes to the matched input elements.  Since <a href="http://www.appelsiini.net/projects/jeditable">Jeditable</a> doesn’t
create these elements until they’re actively being edited, the rules have nothing
to attach to since they don’t exist yet.  Fortunately, <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">jQuery
Validate</a> provides several strategies for defining the rules.  In addition
to being able to attach attributes to the input elements, the rules can be placed
in a separate data structure.  <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">jQuery
Validate</a> refers to these as “static rules”.  Instead of attaching the xVal
rule set directly to the elements, it can be adapted to the static rule set that <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">jQuery
Validate</a> can use directly.  The structure for the ViewModel rules will look
like: 
</p>
        <pre>
          <code>{ rules: { StringRequired: { required: true }, DoubleRange13_100: {
number: true, range: ["13”, "100"] } } messages: { StringRequired: { required: "This
string is required." }, DoubleRange13_100: { range: "Must be between 13 and 100" }
} } </code>
        </pre>
        <p>
        </p>
        <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:3001fb2a-91f4-4e08-93f8-81ab5ca33570" class="wlWriterEditableSmartContent">
          <p>
I've adapted some javascript to do this conversion - it's available <a href="http://popcyclical.com/content/binary/images/jQueryValidateandJeditable_E71E/xValRuleAdapter.js">here</a></p>
        </div>
.  To get the ViewModel’s rules into this format for javascript consumption,
this line is added:<pre><code>&lt;script type="text/javascript"&gt; var validateOptions
= convertXvalToValidateOptions( &lt;%= Html.ClientSideValidationRules&lt;ValidateViewModel&gt;()%&gt;
); &lt;/script&gt; </code></pre><p>
  
</p><p></p><p>
To get these attached to form elements as soon as the user activates them, <a href="http://www.appelsiini.net/projects/jeditable">Jeditable</a>’s
“plugin” feature is utilized:
</p><pre><code>$(function() { // &lt;- on document ready // register plugin with Jeditable
to tie in jQuery Validate $.editable.types['text'].plugin = bindValidate; // attach
Jeditable to each element with class "editable" // Note: this must be done one-by-one
so that the // element's name can be assigned to Jeditable's "name" // option which
is used by jQuery Validate $('.editable').each(function() { var element = $(this);
element.editable( 'SaveUrlOrFunctionGoesHere', { // submit when the element is blurred
onblur: 'submit', onsubmit: jeditableValidate, // assign the name of the input element
// from the element's name - this is needed // because it's what jQuery Validate uses
// to bind the rules to the input element name: element.attr('name') } ); }); });
// Jeditable plugin function bindValidate(settings, self) { // attach jQuery Validate
to // Jeditable's dynamically created form $('form', self).validate(validateOptions);
} // runs before values are submitted to server function jeditableValidate(settings,
self) { // validate the Jeditable dynamically created form return $('form', self).valid();
} </code></pre><p>
With this glue in place, the form elements will now be validated with the rules defined
in the ViewModel.  All fields valid:
</p><p><a href="http://popcyclical.com/content/binary/images/jQueryValidateandJeditable_E71E/jQueryValidateJeditable1.png"><img style="border-right-width: 0px; margin: 0px 0px 0px 20px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="jQueryValidateJeditable1" border="0" alt="jQueryValidateJeditable1" src="http://popcyclical.com/content/binary/images/jQueryValidateandJeditable_E71E/jQueryValidateJeditable1_thumb.png" width="244" height="81" /></a></p><p>
…and here after both have invalid values:
</p><p><a href="http://popcyclical.com/content/binary/images/jQueryValidateandJeditable_E71E/jQueryValidateJeditable2.png"><img style="border-right-width: 0px; margin: 0px 0px 0px 20px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="jQueryValidateJeditable2" border="0" alt="jQueryValidateJeditable2" src="http://popcyclical.com/content/binary/images/jQueryValidateandJeditable_E71E/jQueryValidateJeditable2_thumb.png" width="244" height="77" /></a></p><p>
A few notes:
</p><ul><li>
Any additional options to be sent to <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">jQuery
Validate</a> can be attached to the <code>validateOptions</code> object. I’ve used
this to place all error messages into a separate <code>errorLabelContainer</code> (like <a href="http://stackoverflow.com/questions/61456/mvc-net-jquery-validation">here</a>). 
</li><li>
I feel that AttachValidator function in <code>xVal.jquery.validate.js</code> from
could become more loosely coupled by separating the rule conversion from the DOM element
attachment.</li></ul><p>
I think both of these jQuery libraries provide a great benefit when creating interactive
and helpful forms.  Kudos to <a href="http://bassistance.de/">Jörn Zaefferer</a> and <a href="http://www.appelsiini.net/">Mika
Tuupola</a> for the good work.  xVal is likewise an excellent library – thanks
to <a href="http://www.codeplex.com/site/users/view/SteveSanderson">Steve Sanderson</a>.
</p><img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=417495f7-1ea9-46dc-a3fe-0829928b7a58" /><br /><hr /><a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none">CodeProject</a></body>
      <title>jQuery Validate and Jeditable, Part 2</title>
      <guid isPermaLink="false">http://popcyclical.com/PermaLink,guid,417495f7-1ea9-46dc-a3fe-0829928b7a58.aspx</guid>
      <link>http://popcyclical.com/2010/01/03/jQueryValidateAndJeditablePart2.aspx</link>
      <pubDate>Sun, 03 Jan 2010 05:47:00 GMT</pubDate>
      <description>&lt;p&gt;
When using &lt;a href="http://www.appelsiini.net/projects/jeditable"&gt;Jeditable&lt;/a&gt;, there
is no form element to bind &lt;a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/"&gt;jQuery
Validate&lt;/a&gt; rules with.&amp;nbsp; Instead, when an editable element is clicked or activated,
it dynamically creates a new form and input element and destroys them after the user
is done editing.&amp;nbsp; For the ViewModel from &lt;a href="/2010/01/01/jQueryValidateAndJeditablePart1.aspx"&gt;Part
1&lt;/a&gt;, the View might be rendered like so for &lt;a href="http://www.appelsiini.net/projects/jeditable"&gt;Jeditable&lt;/a&gt;:&lt;pre&gt;&lt;code&gt;&amp;lt;%@
Page Language="C#" Inherits="System.Web.Mvc.ViewPage&amp;lt;ValidateViewModel&amp;gt;" %&amp;gt;
&amp;lt;asp:Content ContentPlaceHolderID="MainContent" runat="server"&amp;gt; &amp;lt;% using(Html.BeginForm())
{%&amp;gt; &amp;lt;%= Html.ValidationSummary() %&amp;gt; &amp;lt;label for="StringRequired"&amp;gt;StringRequired:&amp;lt;/label&amp;gt;
&amp;lt;div class="editable" id="StringRequired" name="StringRequired"&amp;gt; &amp;lt;%= Model.StringRequired
%&amp;gt; &amp;lt;/div&amp;gt; &amp;lt;label for="DoubleRange13_100"&amp;gt;DoulbeRange13_100:&amp;lt;/label&amp;gt;
&amp;lt;div class="editable" id="DoubleRange13_100" name="DoubleRange13_100"&amp;gt; &amp;lt;%=
Model.DoubleRange13_100%&amp;gt; &amp;lt;/div&amp;gt; &amp;lt;%} %&amp;gt; &amp;lt;/asp:Content&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
&lt;a href="http://xval.codeplex.com/"&gt;xVal&lt;/a&gt;’s &lt;code&gt;ClientSideValidation&amp;lt;TViewModel&amp;gt;()&lt;/code&gt; used
in &lt;a href="/2010/01/01/jQueryValidateAndJeditablePart1.aspx"&gt;Part 1&lt;/a&gt; won’t work
to validate this.&amp;nbsp; The reason?&amp;nbsp; It generates a script that binds validation
directly to the form elements on page load.&amp;nbsp; The rendered script looks for the
ViewModel looks like:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;script type="text/javascript"&amp;gt; xVal.AttachValidator(null, {"Fields":[
{ "FieldName":"StringRequired", "FieldRules":[ { "RuleName":"Required", "RuleParameters":{
}, "Message":"This string is required" }, { "FieldName":"DoubleRange13_100", "FieldRules":[
{ "RuleName":"Range", "RuleParameters":{ "Min":"13", "Max":"100", "Type":"decimal"
}, "Message":"Must be between 13 and 100" } ] } ] } ]}, {}) &amp;lt;/script&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
The rules are in the xVal’s StandardJSON format and the &lt;code&gt;AttachValidator&lt;/code&gt; function
(in &lt;code&gt;xVal.jquery.validate.js&lt;/code&gt;) scans the DOM and attaches &lt;a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/"&gt;jQuery
Validate&lt;/a&gt; rules as attributes to the matched input elements.&amp;nbsp; Since &lt;a href="http://www.appelsiini.net/projects/jeditable"&gt;Jeditable&lt;/a&gt; doesn’t
create these elements until they’re actively being edited, the rules have nothing
to attach to since they don’t exist yet.&amp;nbsp; Fortunately, &lt;a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/"&gt;jQuery
Validate&lt;/a&gt; provides several strategies for defining the rules.&amp;nbsp; In addition
to being able to attach attributes to the input elements, the rules can be placed
in a separate data structure.&amp;nbsp; &lt;a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/"&gt;jQuery
Validate&lt;/a&gt; refers to these as “static rules”.&amp;nbsp; Instead of attaching the xVal
rule set directly to the elements, it can be adapted to the static rule set that &lt;a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/"&gt;jQuery
Validate&lt;/a&gt; can use directly.&amp;nbsp; The structure for the ViewModel rules will look
like: &lt;pre&gt;&lt;code&gt;{ rules: { StringRequired: { required: true }, DoubleRange13_100:
{ number: true, range: ["13”, "100"] } } messages: { StringRequired: { required: "This
string is required." }, DoubleRange13_100: { range: "Must be between 13 and 100" }
} } &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:3001fb2a-91f4-4e08-93f8-81ab5ca33570" class="wlWriterEditableSmartContent"&gt;
&lt;p&gt;
I've adapted some javascript to do this conversion - it's available &lt;a href="http://popcyclical.com/content/binary/images/jQueryValidateandJeditable_E71E/xValRuleAdapter.js"&gt;here&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;
.&amp;nbsp; To get the ViewModel’s rules into this format for javascript consumption,
this line is added:&lt;pre&gt;&lt;code&gt;&amp;lt;script type="text/javascript"&amp;gt; var validateOptions
= convertXvalToValidateOptions( &amp;lt;%= Html.ClientSideValidationRules&amp;lt;ValidateViewModel&amp;gt;()%&amp;gt;
); &amp;lt;/script&amp;gt; &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp; 
&lt;p&gt;
&lt;p&gt;
To get these attached to form elements as soon as the user activates them, &lt;a href="http://www.appelsiini.net/projects/jeditable"&gt;Jeditable&lt;/a&gt;’s
“plugin” feature is utilized:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$(function() { // &amp;lt;- on document ready // register plugin with Jeditable
to tie in jQuery Validate $.editable.types['text'].plugin = bindValidate; // attach
Jeditable to each element with class "editable" // Note: this must be done one-by-one
so that the // element's name can be assigned to Jeditable's "name" // option which
is used by jQuery Validate $('.editable').each(function() { var element = $(this);
element.editable( 'SaveUrlOrFunctionGoesHere', { // submit when the element is blurred
onblur: 'submit', onsubmit: jeditableValidate, // assign the name of the input element
// from the element's name - this is needed // because it's what jQuery Validate uses
// to bind the rules to the input element name: element.attr('name') } ); }); });
// Jeditable plugin function bindValidate(settings, self) { // attach jQuery Validate
to // Jeditable's dynamically created form $('form', self).validate(validateOptions);
} // runs before values are submitted to server function jeditableValidate(settings,
self) { // validate the Jeditable dynamically created form return $('form', self).valid();
} &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
With this glue in place, the form elements will now be validated with the rules defined
in the ViewModel.&amp;nbsp; All fields valid:
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://popcyclical.com/content/binary/images/jQueryValidateandJeditable_E71E/jQueryValidateJeditable1.png"&gt;&lt;img style="border-right-width: 0px; margin: 0px 0px 0px 20px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="jQueryValidateJeditable1" border="0" alt="jQueryValidateJeditable1" src="http://popcyclical.com/content/binary/images/jQueryValidateandJeditable_E71E/jQueryValidateJeditable1_thumb.png" width="244" height="81"&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
…and here after both have invalid values:
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://popcyclical.com/content/binary/images/jQueryValidateandJeditable_E71E/jQueryValidateJeditable2.png"&gt;&lt;img style="border-right-width: 0px; margin: 0px 0px 0px 20px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="jQueryValidateJeditable2" border="0" alt="jQueryValidateJeditable2" src="http://popcyclical.com/content/binary/images/jQueryValidateandJeditable_E71E/jQueryValidateJeditable2_thumb.png" width="244" height="77"&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
A few notes:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
Any additional options to be sent to &lt;a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/"&gt;jQuery
Validate&lt;/a&gt; can be attached to the &lt;code&gt;validateOptions&lt;/code&gt; object. I’ve used
this to place all error messages into a separate &lt;code&gt;errorLabelContainer&lt;/code&gt; (like &lt;a href="http://stackoverflow.com/questions/61456/mvc-net-jquery-validation"&gt;here&lt;/a&gt;). 
&lt;li&gt;
I feel that AttachValidator function in &lt;code&gt;xVal.jquery.validate.js&lt;/code&gt; from
could become more loosely coupled by separating the rule conversion from the DOM element
attachment.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
I think both of these jQuery libraries provide a great benefit when creating interactive
and helpful forms.&amp;nbsp; Kudos to &lt;a href="http://bassistance.de/"&gt;Jörn Zaefferer&lt;/a&gt; and &lt;a href="http://www.appelsiini.net/"&gt;Mika
Tuupola&lt;/a&gt; for the good work.&amp;nbsp; xVal is likewise an excellent library – thanks
to &lt;a href="http://www.codeplex.com/site/users/view/SteveSanderson"&gt;Steve Sanderson&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=417495f7-1ea9-46dc-a3fe-0829928b7a58" /&gt;
&lt;br /&gt;
&lt;hr /&gt;
&lt;a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none"&gt;CodeProject&lt;/a&gt;</description>
      <comments>http://popcyclical.com/CommentView,guid,417495f7-1ea9-46dc-a3fe-0829928b7a58.aspx</comments>
      <category>asp.net-mvc</category>
      <category>jquery</category>
    </item>
    <item>
      <trackback:ping>http://popcyclical.com/Trackback.aspx?guid=95f6bac5-f6ba-4cac-a314-ade7536e8af3</trackback:ping>
      <pingback:server>http://popcyclical.com/pingback.aspx</pingback:server>
      <pingback:target>http://popcyclical.com/PermaLink,guid,95f6bac5-f6ba-4cac-a314-ade7536e8af3.aspx</pingback:target>
      <dc:creator>James Kolpack</dc:creator>
      <wfw:comment>http://popcyclical.com/CommentView,guid,95f6bac5-f6ba-4cac-a314-ade7536e8af3.aspx</wfw:comment>
      <wfw:commentRss>http://popcyclical.com/SyndicationService.asmx/GetEntryCommentsRss?guid=95f6bac5-f6ba-4cac-a314-ade7536e8af3</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I was recently tasked to add server-and-client-side form validation for an ASP.NET
MVC site - which already uses in-place editing courtesy <a href="http://www.appelsiini.net/projects/jeditable">Jeditable</a>. 
I really like the field editing experience that Jeditable provides – it makes form
entry in the browser interactive, is fairly straightforward to integrate, and it’s
adaptable to many scenarios.  It does not, however, have any validation mechanism
built in.  
</p>
        <p>
Our project already used <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">jQuery
Validate</a> for a few forms by using the HTML class definitions – like adding <code>class=”required
phone”</code> to an <code>INPUT</code> element.  This works great, but doesn’t
provide any server-side validation tie-in.
</p>
        <p>
Earlier this year, I remembered having seen a <a href="http://speakerrate.com/talks/1218-useful-jquery-tips-tricks-and-plugins-with-asp-net-mvc">presentation</a> by <a href="http://elijahmanor.com/">Elijah
Manor</a> who mentioned using <a href="http://xval.codeplex.com/">xVal</a> for robust
server and client side validation. And with the news that <a href="http://haacked.com/archive/2009/10/01/asp.net-mvc-preview-2-released.aspx">MVC
2 will have a built in validation technique similar to xVal</a>, it was an easy decision
to start investigating this library.
</p>
        <p>
          <a href="http://xval.codeplex.com/">xVal</a> is a pretty easy to get integrated. 
The first step is to decorate the model with validation rules – I’ve decided to use
.NET framework’s <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx">DataAnnotations</a>,
which ends up looking like:
</p>
        <pre>
          <code>public class ValidateViewModel { [Required(ErrorMessage = "This string
is required")] public string StringRequired { get; set; } [Range(13, 100, ErrorMessage
= "Must be between 13 and 100")] public double DoubleRange13_100 { get; set; } }</code>
        </pre>
        <pre>
          <code>public
class ValidatedController { public ViewResult Index() { return View(new ValidateViewModel());
} }</code>
        </pre>
        <pre>
          <code>&lt;%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage&lt;ValidateViewModel&gt;"
%&gt; &lt;asp:Content ContentPlaceHolderID="MainContent" runat="server"&gt; &lt;%
using(Html.BeginForm()) {%&gt; &lt;%= Html.ValidationSummary() %&gt; &lt;label for="StringRequired"&gt;String
Required:&lt;/label&gt; &lt;%= Html.TextBoxFor(m =&gt; m.StringRequired) %&gt; &lt;%=
Html.ValidationMessageFor(m =&gt; m.StringRequired)%&gt; &lt;label for="DoubleRange13_100"&gt;Doulbe
between 13 and 100:&lt;/label&gt; &lt;%= Html.TextBoxFor(m =&gt; m.DoubleRange13_100)
%&gt; &lt;%= Html.ValidationMessageFor(m =&gt; m.DoubleRange13_100)%&gt; &lt;%} %&gt;
&lt;/asp:Content&gt; </code>
        </pre>
        <p>
To validate this ViewModel server side, we use a <a href="http://blog.codeville.net/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/">DataAnnotationsValidationRunner</a> like
the one in xVal’s documentation:
</p>
        <pre>
          <code>[AcceptVerbs(HttpVerbs.Post)] public ActionResult Update(ValidateViewModel
model) { try { DataAnnotationsValidationRunner.ValidateModel(model); // it’s valid,
do the actual update var domainObject = ValidateDomainModel.Find(model.id); Map(model,
domainObject); domainObject.Update(); } catch(RulesException ex) { ex.AddModelStateErrors(ModelState,
null); } return ModelState.IsValid ? RedirectToAction("Completed") : (ActionResult)
View(); }</code>
        </pre>
        <pre>
          <code>public static class DataAnnotationsValidationRunner
{ private static IEnumerable&lt;ErrorInfo&gt; GetErrors(object instance) { return
from prop in TypeDescriptor.GetProperties(instance).Cast&lt;PropertyDescriptor&gt;()
from attribute in prop.Attributes.OfType&lt;ValidationAttribute&gt;() where !attribute.IsValid(prop.GetValue(instance))
select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(String.Empty), instance);
} /// &lt;summary&gt;Validates the given &lt;param name="model"&gt;model&lt;/param&gt;&lt;/summary&gt;
/// &lt;exception cref="RulesException"&gt;Thrown if any errors are found&lt;/exception&gt;
public static void ValidateModel(object model) { var errors = GetErrors(model); if
(errors.Any()) throw new RulesException(errors); } } </code>
        </pre>
        <p>
          <em>Aside: the project uses the </em>
          <a href="http://en.wikipedia.org/wiki/Active_record_pattern">
            <em>Active
record pattern</em>
          </a>
          <em> via </em>
          <a href="http://www.castleproject.org/activerecord/index.html">
            <em>Castle
ActiveRecord</em>
          </a>
          <em> for data access without an intermediate business-logic layer. 
For this case, the rules are defined on the ViewModel and are validated in the controller. 
This does add some noise in the actions – I’m definitely interested in other methods
for handling this. Such as - perhaps the validation could be placed inside the ViewModel?</em>
        </p>
        <p>
The next step is to add client-side validation.  <a href="http://xval.codeplex.com/">xVal</a>’s
built-in <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/">jQuery
Validate</a> rule generator makes this ridiculously simple – just reference <code>jquery.validate.js</code> and <code>xVal.jquery.validate.js</code> in
the view, and then this single line:
</p>
        <pre>
          <code>&lt;%= Html.ClientSideValidation&lt;ValidateViewModel&gt;() %&gt; </code>
        </pre>
        <p>
The rules defined in the ViewModel will now be validated client side and enforced
for server side actions.  This works great for a statically defined HTML form,
but I learned that integrating with <a href="http://www.appelsiini.net/projects/jeditable">Jeditable</a>’s
dynamic inline forms to be not so straight forward. 
</p>
        <p>
Continued in <a href="/2010/01/03/jQueryValidateAndJeditablePart2.aspx">Part 2</a>…
</p>
        <img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=95f6bac5-f6ba-4cac-a314-ade7536e8af3" />
        <br />
        <hr />
        <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none">CodeProject</a>
      </body>
      <title>jQuery Validate and Jeditable, Part 1</title>
      <guid isPermaLink="false">http://popcyclical.com/PermaLink,guid,95f6bac5-f6ba-4cac-a314-ade7536e8af3.aspx</guid>
      <link>http://popcyclical.com/2010/01/01/jQueryValidateAndJeditablePart1.aspx</link>
      <pubDate>Fri, 01 Jan 2010 03:32:00 GMT</pubDate>
      <description>&lt;p&gt;
I was recently tasked to add server-and-client-side form validation for an ASP.NET
MVC site - which already uses in-place editing courtesy &lt;a href="http://www.appelsiini.net/projects/jeditable"&gt;Jeditable&lt;/a&gt;.&amp;nbsp;
I really like the field editing experience that Jeditable provides – it makes form
entry in the browser interactive, is fairly straightforward to integrate, and it’s
adaptable to many scenarios.&amp;nbsp; It does not, however, have any validation mechanism
built in.&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
Our project already used &lt;a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/"&gt;jQuery
Validate&lt;/a&gt; for a few forms by using the HTML class definitions – like adding &lt;code&gt;class=”required
phone”&lt;/code&gt; to an &lt;code&gt;INPUT&lt;/code&gt; element.&amp;nbsp; This works great, but doesn’t
provide any server-side validation tie-in.
&lt;/p&gt;
&lt;p&gt;
Earlier this year, I remembered having seen a &lt;a href="http://speakerrate.com/talks/1218-useful-jquery-tips-tricks-and-plugins-with-asp-net-mvc"&gt;presentation&lt;/a&gt; by &lt;a href="http://elijahmanor.com/"&gt;Elijah
Manor&lt;/a&gt; who mentioned using &lt;a href="http://xval.codeplex.com/"&gt;xVal&lt;/a&gt; for robust
server and client side validation. And with the news that &lt;a href="http://haacked.com/archive/2009/10/01/asp.net-mvc-preview-2-released.aspx"&gt;MVC
2 will have a built in validation technique similar to xVal&lt;/a&gt;, it was an easy decision
to start investigating this library.
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://xval.codeplex.com/"&gt;xVal&lt;/a&gt; is a pretty easy to get integrated.&amp;nbsp;
The first step is to decorate the model with validation rules – I’ve decided to use
.NET framework’s &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx"&gt;DataAnnotations&lt;/a&gt;,
which ends up looking like:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class ValidateViewModel { [Required(ErrorMessage = "This string
is required")] public string StringRequired { get; set; } [Range(13, 100, ErrorMessage
= "Must be between 13 and 100")] public double DoubleRange13_100 { get; set; } }&lt;/code&gt;&lt;/pre&gt;&lt;pre&gt;&lt;code&gt;public
class ValidatedController { public ViewResult Index() { return View(new ValidateViewModel());
} }&lt;/code&gt;&lt;/pre&gt;&lt;pre&gt;&lt;code&gt;&amp;lt;%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage&amp;lt;ValidateViewModel&amp;gt;"
%&amp;gt; &amp;lt;asp:Content ContentPlaceHolderID="MainContent" runat="server"&amp;gt; &amp;lt;%
using(Html.BeginForm()) {%&amp;gt; &amp;lt;%= Html.ValidationSummary() %&amp;gt; &amp;lt;label for="StringRequired"&amp;gt;String
Required:&amp;lt;/label&amp;gt; &amp;lt;%= Html.TextBoxFor(m =&amp;gt; m.StringRequired) %&amp;gt; &amp;lt;%=
Html.ValidationMessageFor(m =&amp;gt; m.StringRequired)%&amp;gt; &amp;lt;label for="DoubleRange13_100"&amp;gt;Doulbe
between 13 and 100:&amp;lt;/label&amp;gt; &amp;lt;%= Html.TextBoxFor(m =&amp;gt; m.DoubleRange13_100)
%&amp;gt; &amp;lt;%= Html.ValidationMessageFor(m =&amp;gt; m.DoubleRange13_100)%&amp;gt; &amp;lt;%} %&amp;gt;
&amp;lt;/asp:Content&amp;gt; &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
To validate this ViewModel server side, we use a &lt;a href="http://blog.codeville.net/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/"&gt;DataAnnotationsValidationRunner&lt;/a&gt; like
the one in xVal’s documentation:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[AcceptVerbs(HttpVerbs.Post)] public ActionResult Update(ValidateViewModel
model) { try { DataAnnotationsValidationRunner.ValidateModel(model); // it’s valid,
do the actual update var domainObject = ValidateDomainModel.Find(model.id); Map(model,
domainObject); domainObject.Update(); } catch(RulesException ex) { ex.AddModelStateErrors(ModelState,
null); } return ModelState.IsValid ? RedirectToAction("Completed") : (ActionResult)
View(); }&lt;/code&gt;&lt;/pre&gt;&lt;pre&gt;&lt;code&gt;public static class DataAnnotationsValidationRunner
{ private static IEnumerable&amp;lt;ErrorInfo&amp;gt; GetErrors(object instance) { return
from prop in TypeDescriptor.GetProperties(instance).Cast&amp;lt;PropertyDescriptor&amp;gt;()
from attribute in prop.Attributes.OfType&amp;lt;ValidationAttribute&amp;gt;() where !attribute.IsValid(prop.GetValue(instance))
select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(String.Empty), instance);
} /// &amp;lt;summary&amp;gt;Validates the given &amp;lt;param name="model"&amp;gt;model&amp;lt;/param&amp;gt;&amp;lt;/summary&amp;gt;
/// &amp;lt;exception cref="RulesException"&amp;gt;Thrown if any errors are found&amp;lt;/exception&amp;gt;
public static void ValidateModel(object model) { var errors = GetErrors(model); if
(errors.Any()) throw new RulesException(errors); } } &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
&lt;em&gt;Aside: the project uses the &lt;/em&gt;&lt;a href="http://en.wikipedia.org/wiki/Active_record_pattern"&gt;&lt;em&gt;Active
record pattern&lt;/em&gt;&lt;/a&gt;&lt;em&gt; via &lt;/em&gt;&lt;a href="http://www.castleproject.org/activerecord/index.html"&gt;&lt;em&gt;Castle
ActiveRecord&lt;/em&gt;&lt;/a&gt;&lt;em&gt; for data access without an intermediate business-logic layer.&amp;nbsp;
For this case, the rules are defined on the ViewModel and are validated in the controller.&amp;nbsp;
This does add some noise in the actions – I’m definitely interested in other methods
for handling this. Such as - perhaps the validation could be placed inside the ViewModel?&lt;/em&gt; 
&lt;/p&gt;
&lt;p&gt;
The next step is to add client-side validation.&amp;nbsp; &lt;a href="http://xval.codeplex.com/"&gt;xVal&lt;/a&gt;’s
built-in &lt;a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/"&gt;jQuery
Validate&lt;/a&gt; rule generator makes this ridiculously simple – just reference &lt;code&gt;jquery.validate.js&lt;/code&gt; and &lt;code&gt;xVal.jquery.validate.js&lt;/code&gt; in
the view, and then this single line:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;%= Html.ClientSideValidation&amp;lt;ValidateViewModel&amp;gt;() %&amp;gt; &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
The rules defined in the ViewModel will now be validated client side and enforced
for server side actions.&amp;nbsp; This works great for a statically defined HTML form,
but I learned that integrating with &lt;a href="http://www.appelsiini.net/projects/jeditable"&gt;Jeditable&lt;/a&gt;’s
dynamic inline forms to be not so straight forward. 
&lt;/p&gt;
&lt;p&gt;
Continued in &lt;a href="/2010/01/03/jQueryValidateAndJeditablePart2.aspx"&gt;Part 2&lt;/a&gt;…
&lt;/p&gt;
&lt;img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=95f6bac5-f6ba-4cac-a314-ade7536e8af3" /&gt;
&lt;br /&gt;
&lt;hr /&gt;
&lt;a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none"&gt;CodeProject&lt;/a&gt;</description>
      <comments>http://popcyclical.com/CommentView,guid,95f6bac5-f6ba-4cac-a314-ade7536e8af3.aspx</comments>
      <category>asp.net-mvc</category>
      <category>jquery</category>
    </item>
  </channel>
</rss>