title: .Net MVC2 How to add error to ModelState when using custom ValidationAttribute
body: <p>I have the following ValidationAttribute class</p>
  
  <pre><code>[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
  public sealed class DateValidationAttribute : ValidationAttribute
  {
      public DateValidationAttribute(string leftDateProperty, CompareOperator compareOperator, string rightDateProperty, string errorMessage)
              : base(errorMessage)
      {
          LeftDateProperty = leftDateProperty;
          Operator = compareOperator;
          RightDateProperty = rightDateProperty;
      }
      ...
      ...
  }
  </code></pre>
  
  <p>It takes two date property names and an operator in the constructor.</p>
  
  <p>In the validation method the result of the statement LeftDate Operator RightDate is returned.</p>
  
  <pre><code>public override bool IsValid(object value)
  {
      DateTime leftDate;
      DateTime rightDate;
  
      // Get all properties on the view model
      PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
  
      DateTime rightDate = (DateTime)properties.Find(RightDateProperty, true).GetValue(value);
      DateTime leftDate = (DateTime)properties.Find(LeftDateProperty, true).GetValue(value);
  
      // Perform rule check
      switch (Operator)
      {
          case CompareOperator.Equal:
              return leftDate.Equals(rightDate);
          case CompareOperator.Greater:                    
              return leftDate &gt; rightDate;
          case CompareOperator.Lesser:                    
              return leftDate &lt; rightDate;
          case CompareOperator.GreaterOrEqual:                    
              return leftDate &gt;= rightDate;
          case CompareOperator.LesserOrEqual:                    
              return leftDate &lt;= rightDate;
          default:
              return false;
      }
  }
  </code></pre>
  
  <p>Because this is an AttriuteTargets.Class attribute I know it is impossible for the framework to know which property that is causing the validation to fail. But I know that it is Left Date Property that is failing and therefore I want to set the Id of the error in the modelstate to this property. The reason for this is that I want the failing field to be marked in the form.</p>
  
  <p><b>Question:</b> How can I modify the error item added to the error collection in ModelState so that its id corresponds to a specific field in the form?</p>