<?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>Martijn Boland &#187; Validation</title>
	<atom:link href="http://blogs.taiga.nl/martijn/tag/validation/feed/" rel="self" type="application/rss+xml" />
	<link>http://blogs.taiga.nl/martijn</link>
	<description>New adventures in .NET</description>
	<lastBuildDate>Tue, 27 Apr 2010 20:51:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Validation in ASP.NET MVC &#8211; part 4: example with server-side and client-side validation</title>
		<link>http://blogs.taiga.nl/martijn/2008/12/08/validation-in-aspnet-mvc-part-4-example-with-server-side/</link>
		<comments>http://blogs.taiga.nl/martijn/2008/12/08/validation-in-aspnet-mvc-part-4-example-with-server-side/#comments</comments>
		<pubDate>Mon, 08 Dec 2008 21:18:15 +0000</pubDate>
		<dc:creator>martijn</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Sample]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://blogs.taiga.nl/martijn/archive/2008/12/08/validation-in-asp.net-mvc-part-4-example-with-server-side.aspx</guid>
		<description><![CDATA[This is part 4 of a series of posts. See also: Validation in ASP.NET MVC &#8211; part 1: basic server-side validation Validation in ASP.NET MVC &#8211; part 2: custom server-side validation Validation in ASP.NET MVC &#8211; part 3: client-side validation with jQuery validation In the previous posts, I described how we implemented model-based validation on [...]]]></description>
			<content:encoded><![CDATA[<p>This is part 4 of a series of posts. See also:</p>
<ul>
<li><a href="http://blogs.taiga.nl/martijn/2008/11/26/validation-in-asp.net-mvc-part-1-basic-server-side-validation">Validation in ASP.NET MVC &#8211; part 1: basic server-side validation</a></li>
<li><a href="http://blogs.taiga.nl/martijn/2008/11/27/validation-in-asp.net-mvc-part-2-custom-server-side-validation">Validation in ASP.NET MVC &#8211; part 2: custom server-side validation</a></li>
<li><a href="http://blogs.taiga.nl/martijn/2008/12/08/validation-in-asp.net-mvc-part-3-client-side-validation-with">Validation in ASP.NET MVC &#8211; part 3: client-side validation with jQuery validation</a></li>
</ul>
<p>In the previous posts, I described how we implemented model-based validation on the server-side in <a href="http://cuyahoga-project.org" target="_blank">Cuyahoga</a> with ASP.NET MVC and as the icing on the cake, we also added some client-side validation (also model-based).</p>
<p>Now, everything can be found in the <a href="https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk/" target="_blank">Cuyahoga SVN sources</a> but I have to agree that it can be a daunting task to check out the complete sources and find all pieces of the validation puzzle. Therefore, I&#8217;ve created a little sample application with everything from the previous posts combined.</p>
<p><a href="http://blogs.taiga.nl/images/blogs_taiga_nl/martijn/WindowsLiveWriter/Val.NETMVCpart4examplewithserversideandc_13761/validation-sample-app_2.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" src="http://blogs.taiga.nl/martijn/wp-content/uploads/subtext/WindowsLiveWriter/Val.NETMVCpart4examplewithserversideandc_13761/validation-sample-app_thumb.png" border="0" alt="validation-sample-app" width="644" height="484" /></a></p>
<p>Hopefully, this will make things a little bit clearer. <a href="http://blogs.taiga.nl/martijn/wp-content/uploads/subtext/MvcValidationSample.zip" target="_blank">You can download the sample app here</a>. Visual Studio 2008 and <a href="http://www.microsoft.com/Downloads/details.aspx?FamilyID=a24d1e00-cd35-4f66-baa0-2362bdde0766&amp;displaylang=en" target="_blank">ASP.NET MVC Beta</a> are required.</p>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.taiga.nl/martijn/2008/12/08/validation-in-aspnet-mvc-part-4-example-with-server-side/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Validation in ASP.NET MVC &#8211; part 3: client-side validation with jquery validation</title>
		<link>http://blogs.taiga.nl/martijn/2008/12/08/validation-in-aspnet-mvc-part-3-client-side-validation-with/</link>
		<comments>http://blogs.taiga.nl/martijn/2008/12/08/validation-in-aspnet-mvc-part-3-client-side-validation-with/#comments</comments>
		<pubDate>Mon, 08 Dec 2008 15:09:19 +0000</pubDate>
		<dc:creator>martijn</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Cuyahoga]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://blogs.taiga.nl/martijn/archive/2008/12/08/validation-in-asp.net-mvc-part-3-client-side-validation-with.aspx</guid>
		<description><![CDATA[This is part 3 of a series of posts. See also: Validation in ASP.NET MVC &#8211; part 1: basic server-side validation Validation in ASP.NET MVC &#8211; part 2: custom server-side validation In the first two parts, I showed how you can perform validation on the server side with Castle Validation attributes and extend that model [...]]]></description>
			<content:encoded><![CDATA[<p>This is part 3 of a series of posts. See also:</p>
<ul>
<li><a href="http://blogs.taiga.nl/martijn/2008/11/26/validation-in-asp.net-mvc-part-1-basic-server-side-validation">Validation in ASP.NET MVC &#8211; part 1: basic server-side validation</a></li>
<li><a href="http://blogs.taiga.nl/martijn/2008/11/27/validation-in-asp.net-mvc-part-2-custom-server-side-validation">Validation in ASP.NET MVC &#8211; part 2: custom server-side validation</a></li>
</ul>
<p>In the first two parts, I showed how you can perform validation on the server side with Castle Validation attributes and extend that model with custom validation logic. With this, we have everything we need to properly validate our model.</p>
<p>For a better user experience though, it would also be nice that we could re-use (part of) our validation logic on the client-side. Luckily, lots of others have already looked into this and the only thing I had to do was to throw everything together and stir it a little bit <img src='http://blogs.taiga.nl/martijn/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<p>The ingredients are:</p>
<ul>
<li><a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/" target="_blank">The jQuery validation plugin</a> (an obvious choice, since we were already using jQuery in <a href="http://cuyahoga-project.org" target="_blank">Cuyahoga</a>);</li>
<li><a href="http://svn.castleproject.org:8080/svn/castle/trunk/MonoRail/Castle.MonoRail.Framework/Helpers/ValidationStrategy" target="_blank">Monorail client-side code generator for jQuery validation</a> (originally contributed by Gildas, but also many credits to the Castle Monorail guys for creating such a flexible infrastructure);</li>
<li><a href="http://blog.codeville.net/2008/04/30/model-based-client-side-validation-for-aspnet-mvc/">Model-based Client-side Validation for ASP.NET MVC</a> (very inspiring blog post by Steve Sanderson).</li>
</ul>
<h3>How it works</h3>
<h3><a href="http://blogs.taiga.nl/martijn/wp-content/uploads/subtext/WindowsLiveWriter/Val.NETMVCpart3clientsidevalidationwithj_CA52/client-side-validation-1_2.png"><img style="border: 0pt none;" src="http://blogs.taiga.nl/martijn/wp-content/uploads/subtext/WindowsLiveWriter/Val.NETMVCpart3clientsidevalidationwithj_CA52/client-side-validation-1_thumb.png" border="0" alt="client-side-validation-1" /></a></h3>
<ol>
<li>The client-side validation is called via an HtmlHelper extension method ClientSideValidation:<br />
&lt;%= Html.ClientSideValidation(ViewData.Model, &#8220;my_form_id&#8221;)%&gt;;</li>
<li>The HtmlHelper extension requests an instance of a BrowserValidationEngine that returns the client script for validation;</li>
<li>BrowserValidationEngine has a reference to an IValidatorRegistry instance that returns all (Castle) validators for the given model;</li>
<li>For each validator, the referenced IBrowserValidatorProvider generates the appropriate client script;</li>
<li>Finally, all generated client script code is combined and sent to the browser in a single javascript block.</li>
</ol>
<p>The existing Monorail codebase proved to be of great value and could be used almost seamlessly. The only difference is the way the client code is generated. Originally, the validators generated css class attributes for the Monorail form helpers, but we don&#8217;t have those with ASP.NET MVC, so all client code is generated as jQuery validation rules.</p>
<p>Below, you can see the output of the validation helper for the new user form in Cuyahoga:</p>
<div style="border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; font-size: 8pt; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">
<div style="border-style: none; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">&lt;script type=<span style="color: #006080">"text/javascript"</span>&gt;</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">$(document).ready(function() {</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">    jQuery.validator.addMethod(<span style="color: #006080">'notEqualTo'</span>, function(<span style="color: #0000ff">value</span>, element, param) { <span style="color: #0000ff">return</span> <span style="color: #0000ff">value</span> != jQuery(param).val(); }, <span style="color: #006080">'Must not be equal to {0}.'</span> );</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">    jQuery.validator.addMethod(<span style="color: #006080">'greaterThan'</span>, function(<span style="color: #0000ff">value</span>, element, param) { <span style="color: #0000ff">return</span> ( IsNaN( <span style="color: #0000ff">value</span> ) &amp;&amp; IsNaN( jQuery(param).val() ) ) || ( <span style="color: #0000ff">value</span> &gt; jQuery(param).val() ); }, <span style="color: #006080">'Must be greater than {0}.'</span> );</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">    jQuery.validator.addMethod(<span style="color: #006080">'lesserThan'</span>, function(<span style="color: #0000ff">value</span>, element, param) { <span style="color: #0000ff">return</span> ( IsNaN( <span style="color: #0000ff">value</span> ) &amp;&amp; IsNaN( jQuery(param).val() ) ) || ( <span style="color: #0000ff">value</span> &lt; jQuery(param).val() ); }, <span style="color: #006080">'Must be lesser than {0}.'</span> );</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">    jQuery.validator.addMethod(<span style="color: #006080">'numberNative'</span>, function(<span style="color: #0000ff">value</span>, element, param) { <span style="color: #0000ff">return</span> <span style="color: #0000ff">this</span>.optional(element) || /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:\,\d+)?$/.test(<span style="color: #0000ff">value</span>); }, <span style="color: #006080">'Not a valid number.'</span> );</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">    jQuery.validator.addMethod(<span style="color: #006080">'simpleDate'</span>, function(<span style="color: #0000ff">value</span>, element, param) { <span style="color: #0000ff">return</span> <span style="color: #0000ff">this</span>.optional(element) || /^\d{1,2}\-\d{1,2}\-\d{4}$/.test(<span style="color: #0000ff">value</span>); }, <span style="color: #006080">'Not a valid date.'</span> );</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">    $(<span style="color: #006080">"#userform"</span>).validate({</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">        rules : {</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">            UserName: {  rangelength: [1, 50] , required: <span style="color: #0000ff">true</span> },</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">            Password: {   required: <span style="color: #0000ff">true</span> , rangelength: [5, 50] , equalTo: <span style="color: #006080">"#PasswordConfirmation"</span> },</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">            PasswordConfirmation: {   equalTo: <span style="color: #006080">"#Password"</span> , rangelength: [5, 50] , required: <span style="color: #0000ff">true</span> },</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">            FirstName: { rangelength: [1, 100] },</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">            LastName: { rangelength: [1, 100] },</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">            Email: {   required: <span style="color: #0000ff">true</span> , rangelength: [1, 100] , email: <span style="color: #0000ff">true</span> },</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">            Website: { rangelength: [1, 100] }</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">        },</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">        messages : {</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">            UserName: {  rangelength: <span style="color: #006080">"The username must be between 1 and 50 characters"</span> , required: <span style="color: #006080">"The username may not be empty"</span> },</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">            Password: {   required: <span style="color: #006080">"The password may not be empty"</span> , rangelength: <span style="color: #006080">"The password must contain at least 5 characters"</span> , equalTo: <span style="color: #006080">"The password must be the same as the confirmation password"</span> },</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">            PasswordConfirmation: {   equalTo: <span style="color: #006080">"The password must be the same as the confirmation password"</span> , rangelength: <span style="color: #006080">"The password must contain at least 5 characters"</span> , required: <span style="color: #006080">"The password confirmation may not be empty"</span> },</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">            FirstName: { rangelength: <span style="color: #006080">"The firstname must be between 1 and 100 characters"</span> },</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">            LastName: { rangelength: <span style="color: #006080">"The lastname must be between 1 and 100 characters"</span> },</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">            Email: {   required: <span style="color: #006080">"E-mail address may not be empty"</span> , rangelength: <span style="color: #006080">"E-mail address must be between 1 and 100 characters"</span> , email: <span style="color: #006080">"Invalid e-mail address"</span> },</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">            Website: { rangelength: <span style="color: #006080">"The website url must be between 1 and 100 characters"</span> }</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">        }</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">    });</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">});</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">&lt;/script&gt;</pre>
</div>
</div>
<p>which results in this:</p>
<p><a href="http://blogs.taiga.nl/martijn/wp-content/uploads/subtext/WindowsLiveWriter/Val.NETMVCpart3clientsidevalidationwithj_CA52/client-side-validation-2_2.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" src="http://blogs.taiga.nl/martijn/wp-content/uploads/subtext/WindowsLiveWriter/Val.NETMVCpart3clientsidevalidationwithj_CA52/client-side-validation-2_thumb.png" border="0" alt="client-side-validation-2" width="644" height="484" /></a></p>
<h3>Summarizing validation</h3>
<p>In this series of posts, I showed how we deal with validation in Cuyahoga and ASP.NET MVC. Personally, I think the nicest part of it is that we have our validation rules centralized and we only have to add one line of code to the view to enable client-side validation.</p>
<p>The code can be found in <a href="https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk/" target="_blank">Cuyahoga SVN</a> and more specifically in the <a href="https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk/Core/Validation/" target="_blank">validation</a> <a href="https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk/Cuyahoga.Web.Mvc/Validation/" target="_blank">sections</a> and the <a href="https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk/Web/Manager/" target="_blank">ASP.NET MVC manager</a>. I&#8217;ll try to make a standalone sample project with all the validation stuff somewhere in the near future.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.taiga.nl/martijn/2008/12/08/validation-in-aspnet-mvc-part-3-client-side-validation-with/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Validation in ASP.NET MVC &#8211; part 2: custom server-side validation</title>
		<link>http://blogs.taiga.nl/martijn/2008/11/27/validation-in-aspnet-mvc-part-2-custom-server-side-validation/</link>
		<comments>http://blogs.taiga.nl/martijn/2008/11/27/validation-in-aspnet-mvc-part-2-custom-server-side-validation/#comments</comments>
		<pubDate>Thu, 27 Nov 2008 13:56:32 +0000</pubDate>
		<dc:creator>martijn</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Cuyahoga]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://blogs.taiga.nl/martijn/archive/2008/11/27/validation-in-asp.net-mvc-part-2-custom-server-side-validation.aspx</guid>
		<description><![CDATA[This is a post in a series of posts. See also: Validation in ASP.NET MVC &#8211; part 1: basic server-side validation In the first post of this series, I showed how you can perform basic server-side validation on your model with help of the Castle Validator component. To summarize this post: the controller validates an [...]]]></description>
			<content:encoded><![CDATA[<p>This is a post in a series of posts. See also:</p>
<ul>
<li><a href="http://blogs.taiga.nl/martijn/2008/11/26/validation-in-asp.net-mvc-part-1-basic-server-side-validation">Validation in ASP.NET MVC &#8211; part 1: basic server-side validation</a></li>
</ul>
<p>In the first post of this series, I showed how you can perform basic server-side validation on your model with help of the <a href="http://hammett.castleproject.org/?p=114" target="_blank">Castle Validator component</a>. To summarize this post: the controller validates an object that is decorated with validation attributes with the help of an IModelValidator component and adds errors to the ModelState.</p>
<p>The first reason to abstract the validator was to prevent coupling of MVC controllers to the Castle Validators. But the abstraction also provides a very nice extension point. We can inject any kind of validator into the controller constructor as long as it implements the IModelValidator interface:</p>
<div style="border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; font-size: 8pt; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">
<div style="border-style: none; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #0000ff">public</span> LoginController(IAuthenticationService authenticationService, IModelValidator&lt;LoginViewData&gt; modelValidator)</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">{</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">    <span style="color: #0000ff">this</span>._authenticationService = authenticationService;</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">    <span style="color: #0000ff">this</span>.ModelValidator = modelValidator;</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">}</pre>
</div>
</div>
<p>In the example above, the constructor requires an IModelValidator&lt;LoginViewData&gt; instance. In our case, <a href="http://www.castleproject.org/container/index.html" target="_blank">Castle Windsor</a> injects a CastleModelValidator&lt;LoginViewData&gt; instance that is registered in the container for IModelValidator&lt;T&gt;. We&#8217;re already seeing the first extension: the IModelValidator interface has a generic inheritor.</p>
<h3>Extending the ModelValidator</h3>
<p>In many scenario&#8217;s, property validation with the generic CastleModelValidator&lt;T&gt; will suffice, but sometimes you&#8217;ll need some extra validation. For example, when creating a new user, we want to check if the username doesn&#8217;t already exist. To perform this check, we created a UserModelValidator class that inherits CastleModelValidator&lt;T&gt;.</p>
<p><a href="http://blogs.taiga.nl/martijn/wp-content/uploads/subtext/WindowsLiveWriter/Val.NETMVCpart2customserversidevalidatio_B94A/validation-custom_2.png"><img style="border: 0pt none;" src="http://blogs.taiga.nl/martijn/wp-content/uploads/subtext/WindowsLiveWriter/Val.NETMVCpart2customserversidevalidatio_B94A/validation-custom_thumb.png" border="0" alt="validation-custom" width="644" height="427" /></a></p>
<p>The CastleModelValidator&lt;T&gt; calls a virtual method PerformValidation() while validating via IsValid(). In UserModelValidator, this method is overriden and performs the check if the username is unique:</p>
<div style="border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; font-size: 8pt; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">
<div style="border-style: none; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> UserModelValidator : CastleModelValidator&lt;User&gt;</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">{</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">    <span style="color: #0000ff">private</span> <span style="color: #0000ff">readonly</span> IUserService _userService;</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"></pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">    <span style="color: #0000ff">public</span> UserModelValidator(IUserService userService)</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">    {</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">        _userService = userService;</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">    }</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"></pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">    <span style="color: #0000ff">protected</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> PerformValidation(User objectToValidate, ICollection&lt;<span style="color: #0000ff">string</span>&gt; includeProperties)</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">    {</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">        <span style="color: #008000">// First validate the property values via the Castle validator.</span></pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">        <span style="color: #0000ff">base</span>.PerformValidation(objectToValidate, includeProperties);</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"></pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">        <span style="color: #008000">// Check username uniqueness.</span></pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">        <span style="color: #0000ff">if</span> (ShouldValidateProperty(<span style="color: #006080">"UserName"</span>, includeProperties)</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">            &amp;&amp; ! String.IsNullOrEmpty(objectToValidate.UserName))</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">        {</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">            <span style="color: #0000ff">if</span> (<span style="color: #0000ff">this</span>._userService.FindUsersByUsername(objectToValidate.UserName).Count &gt; 0)</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">            {</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">                AddError(<span style="color: #006080">"UserName"</span>, <span style="color: #006080">"UserNameValidatorNotUnique"</span>, <span style="color: #0000ff">true</span>);</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">            }</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">        }</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">    }</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">}</pre>
</div>
</div>
<p>Because the modelvalidators are registered in the Windsor Container, we can inject any kind of service or data access component into the validator and thus making it very easy to perform custom validation logic that needs to check the database, or check an external web service.</p>
<h3>Tying things together</h3>
<p>We want the UsersController to use the custom UserModelValidator when ValidateModel() is called. All we have to do is to add UserModelValidator to the constructor of the controller and we&#8217;re done:</p>
<div style="border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; font-size: 8pt; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">
<div style="border-style: none; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #0000ff">public</span> UsersController(IUserService userService, UserModelValidator userModelValidator)</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">{</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">    <span style="color: #0000ff">this</span>._userService = userService;</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">    <span style="color: #0000ff">this</span>.ModelValidator = userModelValidator;</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">}</pre>
</div>
</div>
<p>Finally, this is how it looks in the browser. Nice to see the custom validation error nicely integrated with the rest of the errors.</p>
<p><a href="http://blogs.taiga.nl/martijn/wp-content/uploads/subtext/WindowsLiveWriter/Val.NETMVCpart2customserversidevalidatio_B94A/image_2.png"><img style="border: 0pt none;" src="http://blogs.taiga.nl/martijn/wp-content/uploads/subtext/WindowsLiveWriter/Val.NETMVCpart2customserversidevalidatio_B94A/image_thumb.png" border="0" alt="image" width="644" height="484" /></a></p>
<h3>Other extension possibilities</h3>
<p>In this post we&#8217;ve seen an example where we extended our CastleModelValidator&lt;T&gt; to perform custom logic by calling another service. You might as well call a method on the object itself that is validated to perform custom business logic:</p>
<div style="border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; font-size: 8pt; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">
<div style="border-style: none; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #0000ff">protected</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> PerformValidation(MyClass objectToValidate, ICollection&lt;<span style="color: #0000ff">string</span>&gt; includeProperties)</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">{</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">    <span style="color: #0000ff">base</span>.PerformValidation(objectToValidate, includeProperties);</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;"></pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">    <span style="color: #0000ff">if</span> (! objectToValidate.CheckThatMyBizarreBusinessRuleIsValid())</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">    {</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">        AddError(<span style="color: #006080">"MyProperty"</span>, <span style="color: #006080">"The object to validate is invalid."</span>);</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">    }</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">}</pre>
</div>
</div>
<p>You can also opt for plugging in a completely different library. <a href="http://www.lhotka.net/cslanet/" target="_blank">CSLA</a> fans can very easily implement their own version of IModelValidator&lt;T&gt;, or you could write an IModelValidator&lt;T&gt; implementation that uses the <a href="http://msdn.microsoft.com/en-us/library/cc309320.aspx" target="_blank">Validation Application Block</a> from Enterprise Library.</p>
<h3>The code</h3>
<p>This is a series of posts that is directly inspired by Cuyahoga development. All code can be found in the Cuyahoga SVN trunk at <a href="https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk" target="_blank">https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk</a>. The validation stuff sits in the Validation subdirectory of Cuyahoga.Core: <a href="https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk/Core/Validation" target="_blank">https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk/Core/Validation</a>. Note that Cuyahoga is work in progress. It&#8217;s not guaranteed that the code in SVN will be exactly the same as the sample code in this post.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.taiga.nl/martijn/2008/11/27/validation-in-aspnet-mvc-part-2-custom-server-side-validation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Validation in ASP.NET MVC &#8211; part 1: basic server-side validation</title>
		<link>http://blogs.taiga.nl/martijn/2008/11/26/validation-in-aspnet-mvc-part-1-basic-server-side-validation/</link>
		<comments>http://blogs.taiga.nl/martijn/2008/11/26/validation-in-aspnet-mvc-part-1-basic-server-side-validation/#comments</comments>
		<pubDate>Wed, 26 Nov 2008 12:41:48 +0000</pubDate>
		<dc:creator>martijn</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Cuyahoga]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://blogs.taiga.nl/martijn/archive/2008/11/26/validation-in-asp.net-mvc-part-1-basic-server-side-validation.aspx</guid>
		<description><![CDATA[Almost every single application has to deal with validating user input. With web applications, you can choose to do the validation on the client side or on the server side. In my opinion, validation should at least take place on the server side and optionally on the client side to improve the user experience. Therefore, [...]]]></description>
			<content:encoded><![CDATA[<p>Almost every single application has to deal with validating user input. With web applications, you can choose to do the validation on the client side or on the server side. In my opinion, validation should at least take place on the server side and optionally on the client side to improve the user experience. Therefore, I&#8217;m starting this series of posts with the basic needs: server-side validation.<br />
For some background, also check the excellent <a href="http://blog.codeville.net/2008/09/08/thoughts-on-validation-in-aspnet-mvc-applications/" target="_blank">post about validation by Steve Sanderson</a>.</p>
<h3>Validate the model and not the UI</h3>
<p>In the past I used the ASP.NET WebForms validators. These do a proper job, but are also very much tied to the individual pages, so you have the validation logic scattered all over the place. For Cuyahoga 2, I really wanted a better solution where validation logic is centralized in the model (and removed from the UI layer).<br />
There are already several solutions that make this possible. Microsoft PnP released the <a href="http://msdn.microsoft.com/en-us/library/cc309320.aspx" target="_blank">validation application block</a> and recently (.NET 3.5 SP1), we have the DataAnnotations from ASP.NET Dynamic Data.</p>
<p>In Cuyahoga, we&#8217;re using the <a href="http://hammett.castleproject.org/?p=114" target="_blank">Castle Validator component</a> to perform basic validation, mostly because we&#8217;re already using other components from the Castle stack and it just works fine. With Castle validators, you&#8217;re decorating properties of your Domain entities with attributes like:</p>
<div style="border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; font-size: 8pt; cursor: text; max-height: 200px; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; height: 148px; background-color: #f4f4f4;">
<div style="border-style: none; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">[ValidateNonEmpty(<span style="color: #006080">"UserNameValidatorNonEmpty"</span>)]</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">[ValidateLength(1, 50, <span style="color: #006080">"UserNameValidatorLength"</span>)]</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #0000ff">public</span> <span style="color: #0000ff">virtual</span> <span style="color: #0000ff">string</span> UserName</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">{</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">    get { <span style="color: #0000ff">return</span> <span style="color: #0000ff">this</span>._userName; }</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">    set { <span style="color: #0000ff">this</span>._userName = <span style="color: #0000ff">value</span>; }</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">}</pre>
</div>
</div>
<p>Note that it&#8217;s also possible to decorate DTO&#8217;s or presentation models or whatever you want to call these data containers. In Cuyahoga for example, we have a LoginViewData class that is only used in the UI layer, that is also decorated with validator attributes. If we have a validation infrastructure we might as well (ab)use it <img src='http://blogs.taiga.nl/martijn/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<h3>IModelValidator</h3>
<p>So how are we going to use the Castle validators with ASP.NET MVC?</p>
<p>First we have to make a decision where we want to validate the model. You can do this in the controller or in the service layer (if you one). Some people suggest doing validation in the data access layer but I think the responsibility of a data access layer is persisting and retrieving the model and nothing else.</p>
<p>I&#8217;ve chosen to validate the model from the controller because it&#8217;s a little bit more convenient as you don&#8217;t have to throw exceptions across layers and translate those exceptions to error messages for the user. For validation, all controllers inherit from a base controller that has a <strong>ValidateModel()</strong> method. This controller also has an instance of an <strong>IModelValidator</strong> interface to perform the actual validation, so we don&#8217;t pollute the controller too much with validation logic and also prevent coupling to a specific implementation.</p>
<p><img style="border: 0pt none;" src="http://blogs.taiga.nl/martijn/wp-content/uploads/subtext/WindowsLiveWriter/Val.NETMVCpart1basicserversidevalidation_F58F/validation-controller_3.png" border="0" alt="validation-controller" width="485" height="484" /></p>
<p>At this point, the controller can validate, but to use the Castle validators we have to implement IModelValidator and pass that to the controller. But first: a base controller doesn&#8217;t know which type to validate, but a concrete controller does (assuming we&#8217;re only validating one concrete type in a controller) and therefore we created the IModelValidator&lt;T&gt; interface. The CastleModelValidator&lt;T&gt; class implements this interface.</p>
<p>Because we&#8217;re using the <a href="http://www.castleproject.org/container/index.html" target="_blank">Castle Windsor IoC container</a> we can wire everything together in the controller constructor:</p>
<div style="border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; font-size: 8pt; width: 99.11%; cursor: text; max-height: 200px; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; height: 210px; background-color: #f4f4f4;">
<div style="border-style: none; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> LoginController : BaseController</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">{</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">    <span style="color: #0000ff">private</span> <span style="color: #0000ff">readonly</span> IAuthenticationService _authenticationService;</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">    <span style="color: #008000">/// &lt;summary&gt;</span></pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">    <span style="color: #008000">/// Create and initialize an instance of the LoginController class.</span></pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">    <span style="color: #008000">/// &lt;/summary&gt;</span></pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">    <span style="color: #008000">/// &lt;param name="authenticationService"&gt;The authentication service&lt;/param&gt;</span></pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">    <span style="color: #008000">/// &lt;param name="modelValidator"&gt;The IModelValidator for LoginViewData&lt;/param&gt;</span></pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">    <span style="color: #0000ff">public</span> LoginController(IAuthenticationService authenticationService, IModelValidator&lt;LoginViewData&gt; modelValidator)</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">    {</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">        <span style="color: #0000ff">this</span>._authenticationService = authenticationService;</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">        <span style="color: #0000ff">this</span>.ModelValidator = modelValidator;</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">    }</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">}</pre>
</div>
</div>
<p>In the container is the registered that when asked for an instance of IModelValidator&lt;T&gt;, the container should return an instance of CastleModelValidator&lt;T&gt;. The constructor in the code above, receives an instance of CastleModelValidator&lt;LoginViewData&gt;and sets the ModelValidator of the base controller.</p>
<h3>How it works: the login screen</h3>
<p>The Login action of the LoginController performs validation after populating a LoginViewData instance via TryUpdateModel():</p>
<div style="border: 1px solid gray; margin: 20px 0px 10px; padding: 4px; overflow: auto; font-size: 8pt; width: 98.5%; cursor: text; max-height: 200px; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; height: 174px; background-color: #f4f4f4;">
<div style="border-style: none; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;"><span style="color: #0000ff">public</span> ActionResult Login(<span style="color: #0000ff">string</span> returnUrl)</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">{</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">    var loginUser = <span style="color: #0000ff">new</span> LoginViewData();</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">    <span style="color: #0000ff">try</span></pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">    {</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">        <span style="color: #0000ff">if</span> (TryUpdateModel(loginUser) &amp;&amp; ValidateModel(loginUser))</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: white;">        {</pre>
<pre style="border-style: none; margin: 0em; padding: 0px; overflow: visible; font-size: 8pt; width: 100%; color: black; line-height: 12pt; font-family: consolas,'Courier New',courier,monospace; background-color: #f4f4f4;">             // <span style="color: #0000ff">do</span> authentication and exception handling</pre>
</div>
</div>
<p>ValidateModel() automatically adds all errors to the ASP.NET MVC ModelState, so we have to do very little to actually display the validation errors:</p>
<p><a href="http://blogs.taiga.nl/martijn/wp-content/uploads/subtext/WindowsLiveWriter/Val.NETMVCpart1basicserversidevalidation_F58F/login_2.png"><img style="border: 0pt none;" src="http://blogs.taiga.nl/martijn/wp-content/uploads/subtext/WindowsLiveWriter/Val.NETMVCpart1basicserversidevalidation_F58F/login_thumb.png" border="0" alt="login" width="743" height="550" /></a></p>
<h3>The code</h3>
<p>This is a series of posts that is directly inspired by Cuyahoga development. All code can be found in the Cuyahoga SVN trunk at <a title="https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk" href="https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk">https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk</a>. Please note that all ASP.NET MVC stuff sits in the Manager subdirectory of the Cuyahoga.Web: <a title="https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk/Web/Manager" href="https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk/Web/Manager">https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk/Web/Manager</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.taiga.nl/martijn/2008/11/26/validation-in-aspnet-mvc-part-1-basic-server-side-validation/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
