title: Creating a custom validation through DataAnnotations?
body: <p>Ok so when I want to have a property be validated, I might write something like this:</p>
  
  <pre><code>    [Required]
      [StringLength(255)]
      [DataType(DataType.EmailAddress)]
      [RegularExpression(RegexStrings.Email, ErrorMessage = "Email is not valid.")]
      [DataMember(IsRequired = true, Name="Email", Order = 1)]
      public string Email { get; set; }
  </code></pre>
  
  <p>I like this because in this case, I point it to the regex strings that we have in our common library and specify an error message if it fails. Simple and clean.</p>
  
  <p>My situation is this. This is in a WCF RESTful service. One of the properties that I want validated <em>in this fashion</em> needs to be validated using a custom method which validates using some business logic (it checks the string length and byte length). Can I (and how do i) set up this custom validation so that I can use it like it used in the above example; so it looks something like:</p>
  
  <pre><code>[StreamValidation(ValidationClass, ErrorMessage = "Serial number is invalid")]
  public string Ksn { get; set; }
  </code></pre>
  
  <p>UPDATE:</p>
  
  <p>I have constructed the following class to be my attribute:</p>
  
  <pre><code>[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
  public class KsnValidation : ValidationAttribute
  {
      public override bool IsValid(object value)
      {
          if (!(value is string)) return false;
  
          var val = (string) value;
          var bytes = Enumerable
              .Range(0, val.Length / 2)
              .Select(x =&gt; Byte.Parse(val.Substring(2 * x, 2), NumberStyles.HexNumber))
              .ToArray();
          return val.Length == 20 &amp;&amp; bytes.Length == 10;
      }
  
      public override string FormatErrorMessage(string name)
      {
          return base.FormatErrorMessage(name);
      }
  }
  </code></pre>
  
  <p>Then decorated the following property:</p>
  
  <pre><code>[KsnValidation(ErrorMessage = "Wrong Name")]
  public string Ksn { get; set; }
  </code></pre>
  
  <p>But I'm not sure how to unit test this</p>