<?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/"
	>

<channel>
	<title>devermind.com &#187; dataannotationsmodelbinder</title>
	<atom:link href="http://devermind.com/tag/dataannotationsmodelbinder/feed/" rel="self" type="application/rss+xml" />
	<link>http://devermind.com</link>
	<description>Adrian Grigore's software development weblog. Motto: I will not waste my time looking for a clever motto.</description>
	<lastBuildDate>Fri, 03 Sep 2010 13:25:22 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>ASP.NET MVC Tip #4: Client-side form validation made easy &#8211; Part 2</title>
		<link>http://devermind.com/aspnet-mvc/asp-net-mvc-tip-4-client-side-form-validation-made-easy-part-2/</link>
		<comments>http://devermind.com/aspnet-mvc/asp-net-mvc-tip-4-client-side-form-validation-made-easy-part-2/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 13:00:49 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[client-side form validation]]></category>
		<category><![CDATA[client-side validation]]></category>
		<category><![CDATA[dataannotationsmodelbinder]]></category>
		<category><![CDATA[form validation]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[jQuery.validate]]></category>
		<category><![CDATA[remote validation]]></category>
		<category><![CDATA[xVal]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=219</guid>
		<description><![CDATA[In my previous article about ASP.NET MVC Client-Side validation, I showed how to set up your project so that you don&#8217;t have to write any custom JavaScript code for any new validation rules. This approach also covered remote client-side  validation  &#8211; these are rules which require server-side resource in order if a particular [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://devermind.com/aspnet-mvc/asp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1/">previous article</a> about ASP.NET MVC Client-Side validation, I showed how to set up your project so that you don&#8217;t have to write any custom JavaScript code for any new validation rules. This approach also covered remote client-side  validation  &#8211; these are rules which require server-side resource in order if a particular input field is valid or not.</p>
<p>Since I wrote the first part of the article, Steve Sanderson adopted my idea of automatic client-side validation and baked a similar feature right into the latest version of <a href="http://xval.codeplex.com/">xVal</a>. </p>
<p>One important thing is still missing though: What do you do when validation depends on server-side resources but also involves several different form fields? For example, let&#8217;s assume you were implementing a form for your website users to update their contact information. </p>
<p><span id="more-219"></span></p>
<p><strong>Figure 1 &#8211; Example update form</strong><br />
<a href="http://devermind.com/wp-content/uploads/2010/01/Figure1.png"><img src="http://devermind.com/wp-content/uploads/2010/01/Figure1.png" alt="Figure1 - Example update form" title="Figure1 - Example update form" width="804" height="240" class="alignnone size-full wp-image-220" /></a></p>
<p>The form is very similar to the signup form from the last part of this article. However this time  instead of adding new data to the database, the user needs to update his e-mail address. Validation still has to check that the e-mail address entered does not already exist yet. However, this time  it should ignore the current user&#8217;s e-mail address. </p>
<p>For example, if the current user&#8217;s e-mail address is adrian@lobstersoft.com, then we still want to accept this as valid input. But if he enters &#8220;john@doe.com&#8221; and that e-mail address is already taken, we want client-side validation to fail. </p>
<p><a href="http://devermind.com/wp-content/uploads/2010/01/Figure2.png"><img src="http://devermind.com/wp-content/uploads/2010/01/Figure2.png" alt="Figure 2 -  Client-side validation in action" title="Figure 2 -  Client-side validation in action" width="788" height="234" class="alignnone size-full wp-image-221" /></a></p>
<p>And all of this should of course work automatically on both the server and client side simply by providing a server-side validation rule and attaching it the Viewmodel:</p>
<p>Listing 1 &#8211; ViewModel with client/server side enabled entity validation attribute</p>
<pre class="brush: csharp;">
    [EmailUnique]
    public class UserModel
    {
        public int ID{ get; set;}

        [Required(ErrorMessage = &quot;E-mail address is missing.&quot;)]
        [RegularExpression(EmailRegEx, ErrorMessage = &quot;Invalid e-mail address.&quot;)]
        [EmailUnique]
        public string Email { get; set; }

        public class EmailUniqueAttribute : RemoteEntityValidator
        {
            public EmailUniqueAttribute()
                : base(new string[] { &quot;Email&quot;, &quot;ID&quot; }, typeof(User))
            {
                ErrorMessage = &quot;Someone else has already signed up with this e-mail address.&quot;;
            }

            protected override bool EntityValid(object value)
            {
                User entity = (User)value;
	      //make sure there is no user with a different ID but same e-mail address
                return !new FakeUsersRepository().LoadAll().Any(u =&gt; u.ID != entity.ID &amp;&amp; u.Email == entity.Email);
            }
        }

	// Other UserModel properties and validation attributes...
}
</pre>
<h2>Behind the scenes</h2>
<p>Validation of the e-mail input on this form depends on two variables: The user&#8217;s e-mail address and his user ID. </p>
<p>Therefore we need to:</p>
<p>1. Store the user id as a hidden form input field<br />
2. Provide a client-side Javascript function that creates a remote validation rule that submits all relevant form input fields for the particular validation rule to the server.<br />
3. Provide a server-side action method that triggers the validation attribute&#8217;s IsValid method and returns the result to the client-side remote validator. </p>
<p>The approach is quite similar to remote property validation, except that multiple form input fields have to be provided to the server, but there are also a few other other minor differences. For  example the client-side remote validation rules must also be re-validate when one of the other form input elements that validation depends on is changed.  </p>
<p>But the good news is that all of this can be still solved in a generic way so that you can get away just by coding your server-side data annotation validation attributes &#8211; Very similar to the technique shown in the first part of this article. </p>
<h2>Using the RemoteEntityValidator</h2>
<p>For using the code provided with this article in your own project, proceed as follows: </p>
<p>1. Add Xval, jquery.validate, DataAnnotationModelBinder and the code provided in this article&#8217;s demo project to your project as shown in the first part of this article.<br />
2. Next, whenever you need to write a validation attribute that depends on multiple properties of your view model, derive your validation attribute from RemoteEntityValidator as shown in Listing 1. </p>
<p>These are the differences you have to mind in comparison to the RemotePropertyValidator from the first part of the article:</p>
<p>• The RemoteEntityValidator&#8217;s constructor takes one more variable than the RemotePropertyValidator: A string array of all property names in the ViewModel which are relevant for running the validation rule. I guess this could also be done in a more type-safe way by using Linq expressions, but I chose strings for the sake of a simpler syntax, especially when handling many different form fields. </p>
<p>• Note that even though the RemoteEntityValidator depends on several model properties, you must not apply it to all relevant properties in your model. Just apply it to the ViewModel entity and the property that corresponds to the html input element where you want the client-side validation error to appear. However, you do have to apply it both to the ViewModel property AND to the ViewModel class. The property-level attribute is needed for the triggering client side validation when the input element is changed, and the entity-level attribute is needed for server side validation to work. </p>
<p>• Your html form needs to have an ID attribute. It could be done without, but in my project this led to some problems with client-side validation when the form was reloaded via ajax. That&#8217;s why I changed the client-side code for retrieving form input values to something more stable since posting the first part of this article.  </p>
<p><a href='http://devermind.com/wp-content/uploads/2010/01/RemoteValidation.zip'><strong>Download the demo project</strong></a></p>
<h2>Conclusion</h2>
<p>You have learned how to implement client- and server-side validation in a completely generic, model-oriented way. This part of the article completed the technique shown before with validation attributes that depend on several model properties. </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fdevermind.com%2fwp-admin%2fpost.php%3faction%3dedit%26post%3d219%26message%3d1"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdevermind.com%2fwp-admin%2fpost.php%3faction%3dedit%26post%3d219%26message%3d1" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/ASPNET-MVC-Tip-4-Client-side-form-validation-made-easy-Part-2-devermindcom"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fdevermind.com%2Faspnet-mvc%2Fasp-net-mvc-tip-4-client-side-form-validation-made-easy-part-2%2F" style="border:0px"/></a></p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/aspnet-mvc/asp-net-mvc-tip-4-client-side-form-validation-made-easy-part-2/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC Tip #3: Client-side form validation made easy &#8211; Part 1</title>
		<link>http://devermind.com/aspnet-mvc/asp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1/</link>
		<comments>http://devermind.com/aspnet-mvc/asp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1/#comments</comments>
		<pubDate>Sun, 21 Jun 2009 11:00:58 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[client-side form validation]]></category>
		<category><![CDATA[client-side validation]]></category>
		<category><![CDATA[dataannotationsmodelbinder]]></category>
		<category><![CDATA[form validation]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[jQuery.validate]]></category>
		<category><![CDATA[remote validation]]></category>
		<category><![CDATA[xVal]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=152</guid>
		<description><![CDATA[Client-side form validation has become a de-facto standard for modern web applications. However, replicating server-side validation rules on the client side can be a tedious and error-prone process. 
In addition, there are some validation rules which cannot be checked completely on the client side, for example because the validation depends on information stored in the [...]]]></description>
			<content:encoded><![CDATA[<p>Client-side form validation has become a de-facto standard for modern web applications. However, replicating server-side validation rules on the client side can be a tedious and error-prone process. </p>
<p>In addition, there are some validation rules which cannot be checked completely on the client side, for example because the validation depends on information stored in the server database. For those rules you need to implement remote client-side form validation. </p>
<p>The xVal framework is great for automatic generation of client-side validation code for some of your server-side validation rules, but it does not support remote client-side validation.</p>
<p>This article shows a fully generic way to implement remote client-side form validation so that</p>
<p>• Validation rules remain solely in your ASP.NET MVC model<br />
• You write each validation rule just once, and only in easily testable C# code.  There is no JavaScript or other client-side counterpart .<br />
• There is no need to branch or otherwise modify xVal or jquery.validate<br />
• All you have to do for each new remote form validation rule is to derive from the base class shown in this article.</p>
<p>I&#8217;ll describe how to implement this in detail. I&#8217;ve also uploaded a demo project showing how this works in action. </p>
<p><span id="more-152"></span></p>
<h2>A brief example</h2>
<p>Let&#8217;s assume you are implementing a website signup form. For the sake of simplicity, lets limit the form to asking for an e-mail address and a password. </p>
<p><strong>Figure 1 &#8211; Example signup form</strong></p>
<p><a href="http://devermind.com/wp-content/uploads/2009/06/emptyform.png"><img src="http://devermind.com/wp-content/uploads/2009/06/emptyform.png" alt="emptyform" title="emptyform" width="585" height="186" class="alignnone size-full wp-image-154" /></a></p>
<p>You want to implement the signup form with both client and server side validation. For the e-mail field, let&#8217;s enforce the following validation rules:</p>
<p>1. Email address is not missing<br />
2. Email address looks valid<br />
3. There is no other user with the same e-mail address in your database. </p>
<p>Rules  1 and 2 can easily be checked on the client side. However, rule 3 can only be done with remote validation: Your client-side validation script needs to connect to your web server and ask if the e-mail address is already taken. </p>
<p>In our example, the only user already in the databse shall be adrian@lobstersoft.com. As soon as someone enters this e-mail address in the form and hits tab, return, or the Create button, an error message should appear before the form has even been posted:</p>
<p><strong>Figure 2 &#8211; Error messages should appear before the form has even been posted</strong></p>
<p><a href="http://devermind.com/wp-content/uploads/2009/06/errorform.png"><img src="http://devermind.com/wp-content/uploads/2009/06/errorform.png" alt="errorform" title="errorform" width="613" height="197" class="alignnone size-full wp-image-155" /></a></p>
<p>Listing 1 shows the entire validation logic necessary for both client and server side validation:</p>
<p><strong>Listing 1 &#8211; Signup form client- and server-side  validation rules</strong></p>
<pre class="brush: csharp;">
using System.ComponentModel.DataAnnotations;

namespace RemoteValidation.Models
{
    public class User
    {
        [Required(ErrorMessage = &quot;E-mail address is missing.&quot;)]
        [RegularExpression(EmailRegEx, ErrorMessage = &quot;Invalid e-mail address.&quot;)]
        [IsNew(ErrorMessage = &quot;Someone has already signed up with this e-mail address.&quot;)]
        public string Email { get; set; }

        [Required(ErrorMessage = &quot;Password is missing.&quot;)]
        public string Password { get; set; }

        public class IsNewAttribute : RemotePropertyValidator
        {
            protected override bool PropertyValid(object value)
            {
                return (string)value != &quot;adrian@lobstersoft.com&quot;;
            }
        }

        private const string EmailRegEx = @&quot;^(([^&lt;&gt;()[\]\\.,;:\s@\&quot;&quot;]+&quot;
                                  + @&quot;(\.[^&lt;&gt;()[\]\\.,;:\s@\&quot;&quot;]+)*)|(\&quot;&quot;.+\&quot;&quot;))@&quot;
                                  + @&quot;((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}&quot;
                                  + @&quot;\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+&quot;
                                  + @&quot;[a-zA-Z]{2,}))$&quot;;
    }
}
</pre>
<p>The SignUp action methods should also be easy to implement since the controller does not need to know anything about our validation rules. </p>
<p><strong>Listing 2 &#8211; Signup form action methods</strong></p>
<pre class="brush: csharp;">
         //
        // GET: /Users/SignUp
        public ActionResult SignUp()
        {
            return View(new User());
        }

        //
        // POST: /Users/SignUp
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SignUp(User model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            //Add User to database and start spamming daemon here

            return RedirectToAction(&quot;SignUpComplete&quot;);
        }
</pre>
<p>Lastly, here&#8217;s how the view above is implemented. </p>
<p><strong>Listing 3 &#8211; Signup form view implementation</strong></p>
<pre class="brush: xhtml;">
&lt;%@ Page Title=&quot;&quot; Language=&quot;C#&quot; MasterPageFile=&quot;~/Views/Shared/Site.Master&quot; Inherits=&quot;System.Web.Mvc.ViewPage&lt;RemoteValidation.Models.User&gt;&quot; %&gt;

&lt;asp:Content ID=&quot;Content1&quot; ContentPlaceHolderID=&quot;TitleContent&quot; runat=&quot;server&quot;&gt;
    SignUp
&lt;/asp:Content&gt;
&lt;asp:Content ID=&quot;Content2&quot; ContentPlaceHolderID=&quot;MainContent&quot; runat=&quot;server&quot;&gt;
    &lt;h2&gt;
        SignUp&lt;/h2&gt;
    &lt;%= Html.ValidationSummary(&quot;SignUp was unsuccessful. Please correct the errors and try again.&quot;) %&gt;
    &lt;% using (Html.BeginForm())
       {%&gt;
    &lt;fieldset&gt;
        &lt;legend&gt;Fields&lt;/legend&gt;
        &lt;p&gt;
            &lt;label for=&quot;Email&quot;&gt;
                Enter your e-mail address:&lt;/label&gt;
            &lt;%= Html.TextBox(&quot;Email&quot;)%&gt;
            &lt;%= Html.ValidationMessage(&quot;Email&quot;, &quot;*&quot;)%&gt;
        &lt;/p&gt;
        &lt;p&gt;
            &lt;label for=&quot;Password&quot;&gt;
                Enter a password:&lt;/label&gt;
            &lt;%= Html.Password(&quot;Password&quot;)%&gt;
            &lt;%= Html.ValidationMessage(&quot;Password&quot;, &quot;*&quot;)%&gt;
        &lt;/p&gt;
        &lt;p&gt;
            Hint: To see that remote validation works, try signing up as &quot;adrian@lobstersoft.com&quot;.
        &lt;/p&gt;
        &lt;p&gt;
            &lt;input type=&quot;submit&quot; value=&quot;Create&quot; /&gt;
        &lt;/p&gt;
    &lt;/fieldset&gt;
    &lt;% } %&gt;

    &lt;%= Html.ClientSideValidation&lt;RemoteValidation.Models.User&gt;()%&gt;
&lt;/asp:Content&gt;
</pre>
<p>Note that the View does not contain any JavaScript or other means to specify client-side validation rules. Everything is done transparently and automatically behind the scenes. </p>
<h2>Prerequisites</h2>
<p>In order for this to work, you need to set up a few things first:</p>
<ol>
<li>
Data Annotation validation attributes for server-side validation. IMO this is the best way to handle server-side validation anyway, even if you are not using client-side validation at all. </p>
<p>Brad Wilson has written a great <a href="http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html">blog article</a> on how to use DataAnnotations in ASP.NET MVC.</p>
<p>Note that there is a bug in DataAnnotationModelBinder which might lead to NullReferenceExceptions when using custom ViewModels. This does not become apparent in our demo project, but if you should encounter this problem, you can find a fix in <a href="http://stackoverflow.com/questions/820468/how-does-dataannotationsmodelbinder-work-with-custom-viewmodels">this StackOverflow posting</a>.
</li>
<li>
Download and reference <a href=" http://bassistance.de/jquery-plugins/jquery-plugin-validation/ ">jquery.validate </a>in your Master Page.
</li>
<li>
Download and reference <a href="http://xval.codeplex.com/">xVal</a>  version 0.8 or later in your project. xVal is a great framework for easy implementation of client-side validation in ASP.NET MVC. It transforms standard server-side validation rules into client-side validation rules recognized by jquery.validate. </p>
<p>Steve Sanderson describes how to set it up and use in <a href="http://blog.codeville.net/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/">this blog article</a>.
</li>
</ol>
<p>Once you get this far, you can implement rules 1 and 2 from our example. You could also implement rule 3, although you&#8217;d have to derive it from System.ComponentModel.DataAnnotations.ValidationAttribute, so there would&#8217;t be any client-side validation for that. </p>
<h2>Implementing generic client-side Remote Validation</h2>
<p>While rules 1 and 2 are automagically enforced by xVal on both the client and server side, rule 3 is only checked when the user posts the form. That&#8217;s because xVal does not know what to do with our custom rule. It just looks for standard validation rules like Required, StringLength or RegularExpression and ignores everything else. </p>
<p>Enforcing rule 3 on the client side as well without incurring any additional effort is where the technique I would like to present comes into play.</p>
<p>The first step is not to derive your custom validation rule from ValidationAttribute, but from the RemotePropertyValidator class I implemented. This is already depicted in Listing 1 above. </p>
<p>RemotePropertyValidator is in turn derived from ValidationAttribute, but it also implements xVal&#8217;s ICustomRule interface. This allows it to specify a JavaScript function that should be executed in order to check if the given property is valid on the client side. </p>
<p>RemotePropertyValidator tells xVal to execute the JavaScript function &#8220;RemotePropertyValidation&#8221;. The parameters for this function should be the type of your derived custom validator and the Error message you specified:</p>
<p><strong>Listing 4 &#8211; RemotePropertyValidation class</strong></p>
<pre class="brush: csharp;">
   public abstract class RemotePropertyValidator : ValidationAttribute, ICustomRule
    {
        public CustomRule ToCustomRule()
        {
            return new CustomRule(
                &quot;RemotePropertyValidation&quot;, // JavaScript function name
                new
                    {
                        validator = ToString(),
                        errorMessage = base.ErrorMessage,
                    }, // Params for JavaScript function

                base.ErrorMessage
                );
        }
    }
</pre>
<p>You might be wondering why I am checking for empty  strings / null in Listing 4. That&#8217;s because of differences between how xVal / jquery.validate work on the client side and how the DataAnnotationsModelRunner is implemented on the server side: While it is possible to implicitly implement a Required validator by deriving from ValidationAttribute on the server side, it is not possible to do this with ICustomRule descendents on the client. So I am checking for empty strings / null to avoid inconsistent behaviour. </p>
<p>The ClientSideRegEx property can be set to a regular expression that will be executed on the client before the remote validation is done. You can use it to avoid unnecessary calls to your RemoteValidation controller.</p>
<p>Now, when the user starts typing something in the e-mail field, the browser will execute the JavaScript function &#8220;RemotePropertyValidation&#8221;. Note that this function will receive your derived server-side validator&#8217;s object type and your validator&#8217;s error message  as parameters. </p>
<p>Next, we need to implement a generic RemotePropertyValidation function. In this function we can create a &#8220;remote&#8221; validation rule as supported by jquery.validate and attach it to the Email e-mail input field&#8217;s rules collection:</p>
<p><strong>Listing 5 &#8211; Generic client-side remote validation function</strong></p>
<pre class="brush: javascript;">
function RemotePropertyValidation(value, element, params) {
    var wrappedElement = $(element);
    if (wrappedElement.rules()[&quot;remote&quot;] === undefined) {
        //add optional regEx validator to minimize ajax requests
        if (params.regEx !== null &amp;&amp; wrappedElement.rules()[&quot;xVal_regex&quot;] === undefined) {
            wrappedElement.rules(&quot;add&quot;, {
                xVal_regex: [params.regEx],
                messages: {
                    xVal_regex: params.errorMessage
                }
            });
        }
        var remoteRule =
        //add a new remote validation rule
        wrappedElement.rules(&quot;add&quot;, {
            remote: {
                url: &quot;/RemoteValidation/Property&quot;,
                data: {
                    value: new CreateInputValueAccessor(wrappedElement.attr(&quot;name&quot;)),
                    validator: params.validator
                }
            },
            messages: {
                remote: params.errorMessage
            }
        });

        //validate element again to trigger the new rule(s)
        $(&quot;form&quot;).validate().element(wrappedElement);
    }
    return true;
}

function CreateInputValueAccessor(inputName) {
    return function() {
        return $(&quot;[name=&quot; + inputName + &quot;]&quot;).val();
    };
}
</pre>
<p>The RemotePropertyValidation () function should be referenced in your Master page. Now the first time a user enters something in the Email field , jquery.validate will first validate it using the Required and the Regex rule. If both rules are satisfied, it will check if the e-mail address is already taken with the validation rule that RemotePropertyValidation() inserted on the fly. This will fetch the following URL and parse the JSON reply as validation result.:</p>
<p>http://<Domain>/RemoteValidation/Property?value=<UserInput>&#038;validator=RemoteValidtion.Models.User.IsNew</p>
<p>Now we just need to implement a RemoteValidation that construct an appropriate validator object (note that this is provided in &#8220;validator&#8221; request parameter), let it validate the user input and return the validation result  as JSON: </p>
<p><strong>Listing 6 &#8211; RemoteValidation controller</strong></p>
<pre class="brush: csharp;">
using System;
using System.Reflection;
using System.Web.Mvc;
using RemoteValidation.Models;

namespace RemoteValidation.Controllers
{
    public class RemoteValidationController : Controller
    {
        //
        // GET: /RemoteValidation/Property
        public JsonResult Property()
        {
            Type validatorType = Type.GetType(Request[&quot;validator&quot;], true);
            var validator = (RemotePropertyValidator) Activator.CreateInstance(validatorType);
            return Json(validator.IsValid(Request[&quot;value&quot;]));
        }
    }
}
</pre>
<p>And that&#8217;s it! Now that you have the JavaScript  RemotePropertyValidation function and the remote validation controller in place, all you need to do for new custom validation rules is to derive them from RemotePropertyValidator. This ensures that your validation rules are are automatically enforced on both the server and the client. </p>
<p>For example, all you&#8217;d need to implement for server AND remote client-side validation of password strength is this: </p>
<p><strong>Listing 7 &#8211; Complete implementation of an additional client- and server-side Validator</strong></p>
<pre class="brush: csharp;">
 public class IsSafePasswordAttribute : RemotePropertyValidator
        {

            public IsSafePasswordAttribute()
            {
                //perform some simple password strength check with a regular expression
                //on the client side first
                ClientSideRegEx = &quot;.{8,20}&quot;;
            }

            protected override bool PropertyValid(object value)
            {
                //Insert more elaborate server-side / remote client side password checking
                // logic and return result here...
            }
        }
</pre>
<h2>Caveats</h2>
<p>There are a few things you should keep in mind when using this technique: </p>
<ul>
<li>
You can&#8217;t implicitly implement a Required validator using this technique, so if a property is not optional, you must always decorate it with a Required validator apart from of your own RemotePropertyValidator descendant. It wouldn&#8217;t really make sense to implement a Required validator this way anyway. Please see the Implementation section above if you are interested in the reason for this. </li>
<li>
You can only apply one remote validation rule per form field. This is a limitation of jquery.validate, and it makes sense not to have more than one remote validation rule anyway since you want to minimize the amount of server postbacks as much as possible. If you need to remotely check two different rules on the same property, you can always write a new rule which incorporates both checks, so the only problem is finding an error message that fits both validation rules.
</li>
<li>
This approach only works for Validation Attributes applied to properties, not to entire business entities. I&#8217;ll discuss a similar approach for validating entire business entities in the second part of this article.
</li>
</ul>
<p><a href='http://devermind.com/wp-content/uploads/2009/06/RemoteValidation.zip'>Download the finished demo project </a></p>
<h2>Summary</h2>
<p>Now you know how to implement remote client-side validation without writing any custom JavaScript code.  I discussed how to implement all validation rules, even those that can only be checked on the server, on both the client AND server side in C# code only. I showed how you can do this without any additional effort when implementing new rules. </p>
<p>The only real limitation is that the business rule can check only a single property, not an entire business entity. Stay tuned for the second part of this article, where I&#8217;ll discuss how to circumvent this limitation in a similarly easy way. </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fdevermind.com%2faspnet-mvc%2fasp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdevermind.com%2faspnet-mvc%2fasp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p>
<a rev="vote-for" href="http://dotnetshoutout.com/ASPNET-MVC-Tip-3-How-to-cover-ALL-your-client-side-form-validation-needs-without-writing-any-JavaScript-devermindcom"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fdevermind.com%2Faspnet-mvc%2Fasp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1" style="border:0px"/></a></p>
<p><strong>Edit:</strong> The second part of this article has already been posted <a href="http://devermind.com/aspnet-mvc/asp-net-mvc-tip-4-client-side-form-validation-made-easy-part-2">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/aspnet-mvc/asp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1/feed/</wfw:commentRss>
		<slash:comments>40</slash:comments>
		</item>
	</channel>
</rss>
