﻿<?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>Programming By A Tool &#187; Data Annotations</title>
	<atom:link href="http://byatool.com/tag/data-annotations/feed/" rel="self" type="application/rss+xml" />
	<link>http://byatool.com</link>
	<description>Send all complaints to idontcare@byatool.com.</description>
	<lastBuildDate>Wed, 28 Jul 2010 18:01:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Custom Data Annotations With MVC: How to Check Multiple Properties at One Time</title>
		<link>http://byatool.com/mvc/custom-data-annotations-with-mvc-how-to-check-multiple-properties-at-one-time/</link>
		<comments>http://byatool.com/mvc/custom-data-annotations-with-mvc-how-to-check-multiple-properties-at-one-time/#comments</comments>
		<pubDate>Mon, 21 Dec 2009 22:54:35 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[MVC]]></category>
		<category><![CDATA[Data Annotations]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1162</guid>
		<description><![CDATA[Ok so maybe you read this post and you're thinking to yourself, "I wonder if Diet Dr. Pepper really does taste like regular Dr. Pepper" which of course is silly because the ads clearly say it does. Now you should be asking yourself, "How do I check if two properties have the same value on [...]]]></description>
			<content:encoded><![CDATA[<p>Ok so maybe you read <a href="http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/">this post</a> and you're thinking to yourself, "I wonder if Diet Dr. Pepper really does taste like regular Dr. Pepper" which of course is silly because the ads clearly say it does. Now you should be asking yourself, "How do I check if two properties have the same value on a class with annotation when the property level ones only can check the one property's value?" Kind of wordy way of asking that, but I get what you're asking. Better yet, like usual, I have an answer.</p>
<p>Now what I can swear is that I was no where near the Baxter Building between 1-3 am on Saturday the 15th. I was in fact I was sleeping and have 20 witnesses that can testify. What I can't swear is this is the best way to go about it but it seems to work AND make sense. It's not common for me to come up with solutions that do both.</p>
<pre>  [<span style="color: #008080;">AttributeUsage</span>(<span style="color: #008080;">AttributeTargets</span>.Class)]
  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">PropertiesMatchAttribute </span>: <span style="color: #008080;">ValidationAttribute</span>
  { 

    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> FirstPropertyName { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> SecondPropertyName { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; } 

    <span style="color: #008080;">/<span style="color: #008000;">/Constructor to take in the property names that are supposed to be checked</span></span>
    <span style="color: #0000ff;">public</span> PropertiesMatchAttribute(<span style="color: #008080;">String</span> firstPropertyName, <span style="color: #008080;">String</span> secondPropertyName )
    {
      FirstPropertyName = firstPropertyName;
      SecondPropertyName = secondPropertyName ;
    } 

    <span style="color: #0000ff;">p</span><span style="color: #0000ff;">ublic</span> <span style="color: #0000ff;">override</span> <span style="color: #008080;">Boolean</span> IsValid(<span style="color: #008080;">Object</span> value)
    {
      <span style="color: #008080;">Type</span> objectType = value.GetType();
      <span style="color: #008000;">//Get the property info for the object passed in.  This is the class the attribute is</span>
      <span style="color: #008000;">//  attached to</span>
      <span style="color: #008000;">//I would suggest caching this part... at least the PropertyInfo[]</span>
      <span style="color: #008080;">PropertyInfo</span>[] neededProperties =
        objectType.GetProperties()
        .Where(propertyInfo =&gt; propertyInfo.Name == FirstPropertyName || propertyInfo.Name == SecondPropertyName)
        .ToArray();

      <span style="color: #0000ff;">if</span>(neededProperties.Count() != 2)
      {
        <span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> <span style="color: #008080;">ApplicationException</span>("PropertiesMatchAttribute error on " + objectType.Name);
      }

      <span style="color: #008080;">Boolean</span> isValid = <span style="color: #0000ff;">true</span>;

      <span style="color: #008000;">//Convert both values to string and compare...  Probably could be done better than this</span>
      <span style="color: #008000;">//  but let's not get bogged down with how dumb I am.  We should be concerned about</span>
      <span style="color: #008000;">//  dumb you are, jerkface.</span>
      <span style="color: #0000ff;">if</span>(!<span style="color: #008080;">Convert</span>.ToString(neededProperties[0].GetValue(value, <span style="color: #0000ff;">null</span>)).Equals(<span style="color: #008080;">Convert</span>.ToString(neededProperties[1].GetValue(value, <span style="color: #0000ff;">null</span>))))
      {
        isValid = <span style="color: #0000ff;">false</span>;
      }

      <span style="color: #0000ff;">r</span><span style="color: #0000ff;">eturn</span> isValid;
    }
  }
}</pre>
<p>And then the use:</p>
<pre>  [<span style="color: #008080;">PropertiesMatchAttribute</span>(<span style="color: #800000;">"Password"</span>, <span style="color: #800000;">"ConfirmPassword"</span>, ErrorMessage = <span style="color: #800000;">"Match the passwords, dumb--s."</span>)]
  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">UserCreateModel</span>
  {
     <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> ConfirmPassword{ <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
     <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Password { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<p>Wasn't so hard was it? Normally this would be the part where I degrade you for being bumb because you didn't figure this out but I'm above that now. I guess it must be the holiday season or that I've been told by the board that I should be more gentle with my readers. Guess some were crying after reading some of my posts. Yeah whatever. Bunch of [Removed by Andre].</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/jquery-validation-adding-errors-to-the-error-containter-with-love/" title="jQuery Validation: Adding Errors to the Error Containter&#8230; With Love!">jQuery Validation: Adding Errors to the Error Containter&#8230; With Love!</a></li><li><a href="http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/" title="Data Annotations, MVC, and Why You Might Like Them">Data Annotations, MVC, and Why You Might Like Them</a></li><li><a href="http://byatool.com/lessons/jquery-validation-how-to-use-to-get-rid-of-even-the-toughest-stains/" title="jQuery Validation &#8211; How to Use to Get Rid Of Even The Toughest Stains">jQuery Validation &#8211; How to Use to Get Rid Of Even The Toughest Stains</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/mvc/custom-data-annotations-with-mvc-how-to-check-multiple-properties-at-one-time/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Data Annotations, MVC, and Why You Might Like Them</title>
		<link>http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/</link>
		<comments>http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/#comments</comments>
		<pubDate>Wed, 16 Dec 2009 18:01:40 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Data Annotations]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1155</guid>
		<description><![CDATA[So if you were like me before I knew what Data Annotations were, you most likely would be thinking, "What are Data Annotations?". Well I'm glad I can read your mind and therefore I am glad you asked. Now the fun part about this post is that I might have to admit I was wrong. [...]]]></description>
			<content:encoded><![CDATA[<p>So if you were like me before I knew what Data Annotations were, you most likely would be thinking, "What are Data Annotations?".  Well I'm glad I can read your mind and therefore I am glad you asked.</p>
<p>Now the fun part about this post is that I might have to admit I was wrong.  Why would that be?  Well in <a href="http://byatool.com/pontification/asp-net-mvc-quick-overview-of-controller-structure/">this post</a> I suggested that validation rules would be set in the controller.  Turns out, there is possibly a better place, on the model itself.  How can this be done???  Well that's what you're about to find out.</p>
<p>Say you have a user create model:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> AddUserModel
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> UserName { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Password { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> RepeatPassword { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<p>Now you could have a method on the controller like:</p>
<pre>  <span style="color: #0000ff;">publi</span>c <span style="color: #008080;">ActionResul</span>t AddUser(<span style="color: #008080;">AddUserMode</span>l model)
  {
    <span style="color: #0000ff;">if</span>(IsValid(model))
    {
      ...
    }
  }</pre>
<p>Where you have to create the IsValid method for every model on the controller that you need to validate (And possibly on other controllers if you are sharing models between them...) Or you can have this:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #008080;">ActionResult</span> AddUser(<span style="color: #008080;">AddUserModel</span> model)
  {
    <span style="color: #0000ff;">if</span>(<span style="color: #008080;">ModelState</span>.IsValid)
    {
      ...
    }
  }</pre>
<p>And that is already built in so no validation method needed.  But how is that possible?  Attributes on the model or namely the ValidationAttribute class.</p>
<p>First off you have to include the System.ComponentModel dll in the project.  Simple enough.  Please say you know how to do that or do me a favor and remind yourself to blink. OK done?  Good.</p>
<p>Now you can use some of the built in attributes which is good.  Things like required are nice:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">AddUserModel</span>
  {
    [<span style="color: #008080;">Required</span>]
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> <span style="color: #008080;">UserName</span> { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    ...
  }</pre>
<p>There you go.  Now if the UserName is null or empty, the ModelState will no longer be valid and will fail this check:</p>
<pre>  <span style="color: #008080;">ModelState</span>.IsValid</pre>
<p>Now you might wonder what the error message will be for that?  Honest answer:  I have no f--king clue.  That's why you can actually set it.  Those guys at Microsoft thought of everything.</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">AddUserModel</span>
  {
    [<span style="color: #008080;">Required</span>(ErrorMessage = <span style="color: #800000;">"ENTER A USERNAME IDIOT!"</span>]
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> UserName { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    ...
  }</pre>
<blockquote><p>The guys in the legal department have told me I have to note that your error message should change depending on your use and you shouldn't use the one above.  Whatever.</p></blockquote>
<p>Now you might want to actually pass the errors back, and why wouldn't you?  You're a fine, upstanding, and thoughtful person and I lie like a crook.  The errors, if there are any, are in here:</p>
<pre>  ViewData.ModelState.Values</pre>
<p>And you can use two loops to get to all of them, but I think the parent loop will only run once.</p>
<pre>  <span style="color: #0000ff;">foreach</span> (<span style="color: #008080;">ModelState</span> state <span style="color: #0000ff;">in</span> ViewData.ModelState.Values)
  {
    <span style="color: #0000ff;">foreach</span> (<span style="color: #008080;">ModelErro</span>r error <span style="color: #0000ff;">in</span> state.Errors)
    {
      messageList.Add(error.ErrorMessage);
    }
  }</pre>
<p>Pretty nice huh?  Maybe if you're an idiot who just learned about this.  For cool people like me, it's old news.</p>
<p>What's the point this?  If "this" is data annotations:  Well it helps move some of the validation off the controller if you are looking for a more "Fat model, skinny controller" design which I'm told is a good idea.  This also gets rid of all the validation methods and saves time because of it.</p>
<p>If "this" is your life?  I have no idea.  But if you're to the point that you're asking me about the meaning of your life, you are in some serious trouble.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/" title="ByATool.com gets a shiny new tool!">ByATool.com gets a shiny new tool!</a></li><li><a href="http://byatool.com/lessons/spark-view-engine-asp-net-mvc-and-you/" title="Spark View Engine, ASP.Net MVC, and You">Spark View Engine, ASP.Net MVC, and You</a></li><li><a href="http://byatool.com/mvc/custom-data-annotations-with-mvc-how-to-check-multiple-properties-at-one-time/" title="Custom Data Annotations With MVC: How to Check Multiple Properties at One Time">Custom Data Annotations With MVC: How to Check Multiple Properties at One Time</a></li><li><a href="http://byatool.com/add-on/random-add-on-automapper/" title="Random Add-On &#8211; Automapper">Random Add-On &#8211; Automapper</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
