<?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>Schotime.net &#187; C# MVC Asp.net Validation</title>
	<atom:link href="http://schotime.net/blog/index.php/tag/c-mvc-aspnet-validation/feed/" rel="self" type="application/rss+xml" />
	<link>http://schotime.net/blog</link>
	<description>All Things .Net and Me</description>
	<lastBuildDate>Thu, 01 Jul 2010 14:42:28 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Validation with Asp.net MVC, xVal &amp; IDataerrorInfo</title>
		<link>http://schotime.net/blog/index.php/2009/03/05/validation-with-aspnet-mvc-xval-idataerrorinfo/</link>
		<comments>http://schotime.net/blog/index.php/2009/03/05/validation-with-aspnet-mvc-xval-idataerrorinfo/#comments</comments>
		<pubDate>Thu, 05 Mar 2009 11:46:07 +0000</pubDate>
		<dc:creator>Schotime</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C# MVC Asp.net Validation]]></category>

		<guid isPermaLink="false">http://schotime.net/blog/index.php/2009/03/05/validation-with-aspnet-mvc-xval-idataerrorinfo/</guid>
		<description><![CDATA[I&#8217;ve been playing around with lots of different Validation concepts recently and I think I have come up with something that will be very useful. Hopefully you will also find it useful.
Firstly I have been looking at Steve Sanderson&#8217;s new open source project xVal and decided that it was a good place to start. I [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been playing around with lots of different Validation concepts recently and I think I have come up with something that will be very useful. Hopefully you will also find it useful.</p>
<p>Firstly I have been looking at <a href="http://blog.codeville.net/2009/02/27/xval-08-beta-now-released/" target="_blank" onclick="pageTracker._trackPageview('/outgoing/blog.codeville.net/2009/02/27/xval-08-beta-now-released/?referer=');">Steve Sanderson</a>&#8217;s new open source project <a href="http://www.codeplex.com/xval" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.codeplex.com/xval?referer=');">xVal</a> and decided that it was a good place to start. I was mainly looking at server side validation but <a href="http://www.codeplex.com/xval" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.codeplex.com/xval?referer=');">xVal</a> can also generate script to enable client side validation.</p>
<p>Firstly I&#8217;ll show you how I integrated the DataAnnotations validation pack that Dynamic data uses and is available to us in 3.5sp1 as far as I know.</p>
<table cellspacing="0" cellpadding="2" width="400" border="1">
<tbody>
<tr>
<td style="background: black" valign="top" width="400">
<pre class="code"><span style="background: black; color: #cc7832">public class </span><span style="background: black; color: #ffc66d">CustomValidation </span><span style="background: black; color: white">: </span><span style="background: black; color: #6897bb">IDataErrorInfo
</span><span style="background: black; color: white">{
    </span><span style="background: black; color: #cc7832">string </span><span style="background: black; color: #6897bb">IDataErrorInfo</span><span style="background: black; color: white">.Error
    {
        </span><span style="background: black; color: #cc7832">get
        </span><span style="background: black; color: white">{
            </span><span style="background: black; color: #cc7832">return string</span><span style="background: black; color: white">.Empty;
        }
    }

    </span><span style="background: black; color: #cc7832">string </span><span style="background: black; color: #6897bb">IDataErrorInfo</span><span style="background: black; color: white">.</span><span style="background: black; color: #cc7832">this</span><span style="background: black; color: white">[</span><span style="background: black; color: #cc7832">string </span><span style="background: black; color: white">columnName]
    {
        </span><span style="background: black; color: #cc7832">get
        </span><span style="background: black; color: white">{
            </span><span style="background: black; color: #ffc66d">List</span><span style="background: black; color: white">&lt;</span><span style="background: black; color: #ffc66d">ErrorInfo</span><span style="background: black; color: white">&gt; errors =
                </span><span style="background: black; color: #ffc66d">DataAnnotations</span><span style="background: black; color: white">.GetErrors(</span><span style="background: black; color: #cc7832">this</span><span style="background: black; color: white">, columnName).ToList();
            </span><span style="background: black; color: #cc7832">return </span><span style="background: black; color: white">errors.Count &gt; </span><span style="background: black; color: #6897bb">0 </span><span style="background: black; color: white">? errors[</span><span style="background: black; color: #6897bb">0</span><span style="background: black; color: white">].ErrorMessage : </span><span style="background: black; color: #cc7832">null</span><span style="background: black; color: white">;
        }
    }
}</span></pre>
</td>
</tr>
</tbody>
</table>
<p>So I first created a class called CustomValidation that implements the IDataErrorInfo interface. From here only two Properties need to be set, the second one being the most important. Here I use the get property accessor to check the errors for each column and if there are errors I return the error message for the first error.</p>
<p>From here we need our Model that we want validated to inherit from this class as follows.</p>
<table cellspacing="0" cellpadding="2" width="400" border="1">
<tbody>
<tr>
<td style="background: black" valign="top" width="400">
<pre class="code"><span style="background: black; color: white">    </span><span style="background: black; color: #cc7832">public class </span><span style="background: black; color: #ffc66d">MyProduct </span><span style="background: black; color: white">: </span><span style="background: black; color: #ffc66d">CustomValidation
    </span><span style="background: black; color: white">{
        [</span><span style="background: black; color: #ffc66d">Range</span><span style="background: black; color: white">(</span><span style="background: black; color: #6897bb">0</span><span style="background: black; color: white">, </span><span style="background: black; color: #6897bb">100</span><span style="background: black; color: white">, ErrorMessage=</span><span style="background: black; color: #a5c25c">"{0} must be set between {1} and {2}"</span><span style="background: black; color: white">)]
        </span><span style="background: black; color: #cc7832">public double</span><span style="background: black; color: white">? UnitPrice { </span><span style="background: black; color: #cc7832">get</span><span style="background: black; color: white">; </span><span style="background: black; color: #cc7832">set</span><span style="background: black; color: white">; }

        [</span><span style="background: black; color: #ffc66d">StringLength</span><span style="background: black; color: white">(</span><span style="background: black; color: #6897bb">30</span><span style="background: black; color: white">)]
        </span><span style="background: black; color: #cc7832">public string </span><span style="background: black; color: white">ProductName { </span><span style="background: black; color: #cc7832">get</span><span style="background: black; color: white">; </span><span style="background: black; color: #cc7832">set</span><span style="background: black; color: white">; }

        </span><span style="background: black; color: #cc7832">public </span><span style="background: black; color: #ffc66d">List</span><span style="background: black; color: white">&lt;</span><span style="background: black; color: #ffc66d">MyOrder</span><span style="background: black; color: white">&gt; Orders { </span><span style="background: black; color: #cc7832">get</span><span style="background: black; color: white">; </span><span style="background: black; color: #cc7832">set</span><span style="background: black; color: white">; }
    }

    </span><span style="background: black; color: #cc7832">public class </span><span style="background: black; color: #ffc66d">MyOrder </span><span style="background: black; color: white">: </span><span style="background: black; color: #ffc66d">CustomValidation
    </span><span style="background: black; color: white">{
        [</span><span style="background: black; color: #ffc66d">Required</span><span style="background: black; color: white">]
        </span><span style="background: black; color: #cc7832">public string </span><span style="background: black; color: white">Name { </span><span style="background: black; color: #cc7832">get</span><span style="background: black; color: white">; </span><span style="background: black; color: #cc7832">set</span><span style="background: black; color: white">; }
    }</span></pre>
</td>
</tr>
</tbody>
</table>
<p>We can then attach Validation attributes. <strong>note:</strong> you will need to add a reference to the System.ComponentModel.DataAnnotations assembly for these attributes to show up.</p>
<p>Once we have these two things setup we can start using it. Actually before I start I will show you the DataAnnotations.GetErrors methods.</p>
<table cellspacing="0" cellpadding="2" width="400" border="1">
<tbody>
<tr>
<td style="background: black" valign="top" width="400">
<pre class="code"><span style="background: black; color: #cc7832">public static class </span><span style="background: black; color: #ffc66d">DataAnnotations
</span><span style="background: black; color: white">{
    </span><span style="background: black; color: #cc7832">public static </span><span style="background: black; color: #6897bb">IEnumerable</span><span style="background: black; color: white">&lt;</span><span style="background: black; color: #ffc66d">ErrorInfo</span><span style="background: black; color: white">&gt; GetErrors(</span><span style="background: black; color: #cc7832">object </span><span style="background: black; color: white">instance)
    {
        </span><span style="background: black; color: #cc7832">return </span><span style="background: black; color: white">GetErrors(instance, </span><span style="background: black; color: #cc7832">null</span><span style="background: black; color: white">);
    }

    </span><span style="background: black; color: #cc7832">public static </span><span style="background: black; color: #6897bb">IEnumerable</span><span style="background: black; color: white">&lt;</span><span style="background: black; color: #ffc66d">ErrorInfo</span><span style="background: black; color: white">&gt; GetErrors(</span><span style="background: black; color: #cc7832">object </span><span style="background: black; color: white">instance, </span><span style="background: black; color: #cc7832">string </span><span style="background: black; color: white">name)
    {
        </span><span style="background: black; color: #cc7832">var </span><span style="background: black; color: white">metadataAttrib = instance.GetType()
                .GetCustomAttributes(</span><span style="background: black; color: #cc7832">typeof</span><span style="background: black; color: white">(</span><span style="background: black; color: #ffc66d">MetadataTypeAttribute</span><span style="background: black; color: white">), </span><span style="background: black; color: #cc7832">true</span><span style="background: black; color: white">)
                .OfType&lt;</span><span style="background: black; color: #ffc66d">MetadataTypeAttribute</span><span style="background: black; color: white">&gt;().FirstOrDefault();
        </span><span style="background: black; color: #cc7832">var </span><span style="background: black; color: white">buddyClassOrModelClass = metadataAttrib != </span><span style="background: black; color: #cc7832">null
                </span><span style="background: black; color: white">? metadataAttrib.MetadataClassType
                : instance.GetType();
        </span><span style="background: black; color: #cc7832">var </span><span style="background: black; color: white">buddyClassProperties = </span><span style="background: black; color: #ffc66d">TypeDescriptor</span><span style="background: black; color: white">.GetProperties(buddyClassOrModelClass)
            .Cast&lt;</span><span style="background: black; color: #ffc66d">PropertyDescriptor</span><span style="background: black; color: white">&gt;();
        </span><span style="background: black; color: #cc7832">var </span><span style="background: black; color: white">modelClassProperties = </span><span style="background: black; color: #ffc66d">TypeDescriptor</span><span style="background: black; color: white">.GetProperties(instance.GetType())
            .Cast&lt;</span><span style="background: black; color: #ffc66d">PropertyDescriptor</span><span style="background: black; color: white">&gt;();

        </span><span style="background: black; color: #cc7832">var </span><span style="background: black; color: white">list = </span><span style="background: black; color: #cc7832">from </span><span style="background: black; color: white">buddyProp </span><span style="background: black; color: #cc7832">in </span><span style="background: black; color: white">buddyClassProperties
                   </span><span style="background: black; color: #cc7832">join </span><span style="background: black; color: white">modelProp </span><span style="background: black; color: #cc7832">in </span><span style="background: black; color: white">modelClassProperties </span><span style="background: black; color: #cc7832">on
                            </span><span style="background: black; color: white">buddyProp.Name </span><span style="background: black; color: #cc7832">equals </span><span style="background: black; color: white">modelProp.Name
                   </span><span style="background: black; color: #cc7832">from </span><span style="background: black; color: white">attribute </span><span style="background: black; color: #cc7832">in </span><span style="background: black; color: white">buddyProp.Attributes.OfType&lt;</span><span style="background: black; color: #ffc66d">ValidationAttribute</span><span style="background: black; color: white">&gt;()
                   </span><span style="background: black; color: #cc7832">where </span><span style="background: black; color: white">!attribute.IsValid(modelProp.GetValue(instance))
                   </span><span style="background: black; color: #cc7832">select new </span><span style="background: black; color: #ffc66d">ErrorInfo</span><span style="background: black; color: white">(
                       buddyProp.Name,
                       attribute.FormatErrorMessage(modelProp.Name),
                       instance);

        </span><span style="background: black; color: #cc7832">if </span><span style="background: black; color: white">(name != </span><span style="background: black; color: #cc7832">null</span><span style="background: black; color: white">)
            list = list.Where(x =&gt; x.PropertyName == name);

        </span><span style="background: black; color: #cc7832">return </span><span style="background: black; color: white">list;
    }
}</span></pre>
</td>
</tr>
</tbody>
</table>
<p>note: you will need the using statement and a reference to the xVal.dll<br /><span style="background: black; color: #cc7832">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; using </span><span style="background: black; color: white">xVal.ServerSide;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></p>
<p><a href="http://11011.net/software/vspaste" onclick="pageTracker._trackPageview('/outgoing/11011.net/software/vspaste?referer=');"></a></p>
<p>Now we can start.<br />Here is are sample controller actions. Creating a MyProduct and sending it to the view. Then accepting a MyProduct when the form gets posted back.</p>
<table cellspacing="0" cellpadding="2" width="400" border="1">
<tbody>
<tr>
<td style="background: black" valign="top" width="400">
<pre class="code"><span style="background: black; color: #cc7832">public </span><span style="background: black; color: #ffc66d">ActionResult </span><span style="background: black; color: white">ValidationTest()
{
    </span><span style="background: black; color: #ffc66d">MyProduct </span><span style="background: black; color: white">p = </span><span style="background: black; color: #cc7832">new </span><span style="background: black; color: #ffc66d">MyProduct</span><span style="background: black; color: white">()
    {
        ProductName = </span><span style="background: black; color: #a5c25c">"Magazine"</span><span style="background: black; color: white">,
        UnitPrice = </span><span style="background: black; color: #6897bb">23
    </span><span style="background: black; color: white">};

    p.Orders = </span><span style="background: black; color: #cc7832">new </span><span style="background: black; color: #ffc66d">List</span><span style="background: black; color: white">&lt;</span><span style="background: black; color: #ffc66d">MyOrder</span><span style="background: black; color: white">&gt;();
    p.Orders.Add(</span><span style="background: black; color: #cc7832">new </span><span style="background: black; color: #ffc66d">MyOrder </span><span style="background: black; color: white">{ Name = </span><span style="background: black; color: #a5c25c">"Robert King" </span><span style="background: black; color: white">});

    </span><span style="background: black; color: #cc7832">return </span><span style="background: black; color: white">View(p);
}</span></pre>
<pre class="code"><span style="background: black; color: white">[</span><span style="background: black; color: #ffc66d">AcceptVerbs</span><span style="background: black; color: white">(</span><span style="background: black; color: #6897bb">HttpVerbs</span><span style="background: black; color: white">.Post)]
</span><span style="background: black; color: #cc7832">public </span><span style="background: black; color: #ffc66d">ActionResult </span><span style="background: black; color: white">ValidationTest(</span><span style="background: black; color: #ffc66d">MyProduct </span><span style="background: black; color: white">product)
{
    </span><span style="background: black; color: #cc7832">if </span><span style="background: black; color: white">(ModelState.IsValid)
    {
        </span><span style="background: black; color: #cc7832">return </span><span style="background: black; color: white">RedirectToAction(</span><span style="background: black; color: #a5c25c">"ValidationTest"</span><span style="background: black; color: white">);
    }

    </span><span style="background: black; color: #cc7832">return </span><span style="background: black; color: white">View(product);
}</span></pre>
</td>
</tr>
</tbody>
</table>
<p>In the latter action method the product argument has already been validated by the time it arrives at the if statement. All that needs to be done is to check if the Modelstate is valid and if it is redirect back to the page else display the posted data back to the user with the errors in Modelstate.</p>
<p>Here is what the view looks like.</p>
<table cellspacing="0" cellpadding="2" width="400" border="1">
<tbody>
<tr>
<td style="background: black" valign="top" width="400">
<pre class="code"><span style="background: black; color: white">&lt;</span><span style="background: black; color: #e8bc64">h2</span><span style="background: black; color: white">&gt;Custom Validation&lt;/</span><span style="background: black; color: #e8bc64">h2</span><span style="background: black; color: white">&gt;

</span><span style="background: black; color: #6897bb">&lt;%</span><span style="background: black; color: white">= Html.ValidationSummary() </span><span style="background: black; color: #6897bb">%&gt;

&lt;% </span><span style="background: black; color: #cc7832">using </span><span style="background: black; color: white">(Html.BeginForm()) { </span><span style="background: black; color: #6897bb">%&gt;

    </span><span style="background: black; color: white">&lt;</span><span style="background: black; color: #e8bc64">div </span><span style="background: black; color: white">style=</span><span style="background: black; color: #a5c25c">"</span><span style="background: black; color: #fcf4be">padding-left</span><span style="background: black; color: white">: 15px</span><span style="background: black; color: #a5c25c">"</span><span style="background: black; color: white">&gt;
        &lt;</span><span style="background: black; color: #e8bc64">div</span><span style="background: black; color: white">&gt;
            Unit Price: </span><span style="background: black; color: #6897bb">&lt;%</span><span style="background: black; color: white">= Html.TextBox(</span><span style="background: black; color: #a5c25c">"product.UnitPrice"</span><span style="background: black; color: white">, Model.UnitPrice)</span><span style="background: black; color: #6897bb">%&gt;
            &lt;%</span><span style="background: black; color: white">= Html.ValidationMessage(</span><span style="background: black; color: #a5c25c">"product.UnitPrice"</span><span style="background: black; color: white">)</span><span style="background: black; color: #6897bb">%&gt;
        </span><span style="background: black; color: white">&lt;/</span><span style="background: black; color: #e8bc64">div</span><span style="background: black; color: white">&gt;
        &lt;</span><span style="background: black; color: #e8bc64">div</span><span style="background: black; color: white">&gt;
            Product Name: </span><span style="background: black; color: #6897bb">&lt;%</span><span style="background: black; color: white">= Html.TextBox(</span><span style="background: black; color: #a5c25c">"product.ProductName"</span><span style="background: black; color: white">, Model.ProductName)</span><span style="background: black; color: #6897bb">%&gt;
             &lt;%</span><span style="background: black; color: white">= Html.ValidationMessage(</span><span style="background: black; color: #a5c25c">"product.ProductName"</span><span style="background: black; color: white">)</span><span style="background: black; color: #6897bb">%&gt;
        </span><span style="background: black; color: white">&lt;/</span><span style="background: black; color: #e8bc64">div</span><span style="background: black; color: white">&gt;
        &lt;</span><span style="background: black; color: #e8bc64">div</span><span style="background: black; color: white">&gt;
            Orders:
            </span><span style="background: black; color: #6897bb">&lt;% </span><span style="background: black; color: #cc7832">int </span><span style="background: black; color: white">j = </span><span style="background: black; color: #6897bb">0</span><span style="background: black; color: white">;
               </span><span style="background: black; color: #cc7832">foreach </span><span style="background: black; color: white">(</span><span style="background: black; color: #ffc66d">MyOrder </span><span style="background: black; color: white">o </span><span style="background: black; color: #cc7832">in </span><span style="background: black; color: white">Model.Orders) { </span><span style="background: black; color: #6897bb">%&gt;
               </span><span style="background: black; color: white">&lt;</span><span style="background: black; color: #e8bc64">div  </span><span style="background: black; color: white">style=</span><span style="background: black; color: #a5c25c">"</span><span style="background: black; color: #fcf4be">padding-left</span><span style="background: black; color: white">: 15px</span><span style="background: black; color: #a5c25c">"</span><span style="background: black; color: white">&gt;
                    </span><span style="background: black; color: #6897bb">&lt;%</span><span style="background: black; color: white">= j + </span><span style="background: black; color: #6897bb">1 %&gt;</span><span style="background: black; color: white">. </span><span style="background: black; color: #6897bb">&lt;%</span><span style="background: black; color: white">= Html.TextBox(</span><span style="background: black; color: #a5c25c">"product.Orders[" </span><span style="background: black; color: white">+ j + </span><span style="background: black; color: #a5c25c">"].Name"</span><span style="background: black; color: white">, o.Name)</span><span style="background: black; color: #6897bb">%&gt;
                    &lt;%</span><span style="background: black; color: white">= Html.ValidationMessage(</span><span style="background: black; color: #a5c25c">"product.Orders[" </span><span style="background: black; color: white">+ j + </span><span style="background: black; color: #a5c25c">"].Name"</span><span style="background: black; color: white">)</span><span style="background: black; color: #6897bb">%&gt;</span><span style="background: black; color: white">&lt;</span><span style="background: black; color: #e8bc64">br </span><span style="background: black; color: white">/&gt;
                    </span><span style="background: black; color: #6897bb">&lt;% </span><span style="background: black; color: white">j++; </span><span style="background: black; color: #6897bb">%&gt;
               </span><span style="background: black; color: white">&lt;/</span><span style="background: black; color: #e8bc64">div</span><span style="background: black; color: white">&gt;
            </span><span style="background: black; color: #6897bb">&lt;% </span><span style="background: black; color: white">} </span><span style="background: black; color: #6897bb">%&gt;
        </span><span style="background: black; color: white">&lt;/</span><span style="background: black; color: #e8bc64">div</span><span style="background: black; color: white">&gt;
    &lt;/</span><span style="background: black; color: #e8bc64">div</span><span style="background: black; color: white">&gt;

    &lt;</span><span style="background: black; color: #e8bc64">br </span><span style="background: black; color: white">/&gt;
    &lt;</span><span style="background: black; color: #e8bc64">input </span><span style="background: black; color: white">type=</span><span style="background: black; color: #a5c25c">"submit" </span><span style="background: black; color: white">/&gt;

</span><span style="background: black; color: #6897bb">&lt;% </span><span style="background: black; color: white">} </span><span style="background: black; color: #6897bb">%&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste" onclick="pageTracker._trackPageview('/outgoing/11011.net/software/vspaste?referer=');"></a></td>
</tr>
</tbody>
</table>
<p>Not that this even works when complex binding lists to that have been posted. I&#8217;ll try and get a full working example for download here as well if I get enough interest.</p>
<p>And that&#8217;s it. In upcoming posts I&#8217;ll show you how:</p>
<ul>
<li>To do the validation without using the IDataErrorInfo interface and its automatic binding.
<li>Use the methods that come with <a href="http://www.codeplex.com/xval" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.codeplex.com/xval?referer=');">xVal</a> to implement some client side validation.
<li>How to create your own validation attributes.
<li>Plugging in Castle Validator or other supported validators into <a href="http://www.codeplex.com/xval" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.codeplex.com/xval?referer=');">xVal</a>.</li>
</ul>
<p>Hope this helps you get started with Validation in Asp.net MVC.</p>
<p>Cheers,<br />Adam</p>
]]></content:encoded>
			<wfw:commentRss>http://schotime.net/blog/index.php/2009/03/05/validation-with-aspnet-mvc-xval-idataerrorinfo/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>
