title: How to use DataAnnotation attributes for validating a model in a console app
body: <p>I'm attempting to use DataAnnotation attribute validation outside of an ASP.net MVC application.  Ideally I'd like to take any model class in my console application and decorate it as follows:</p>
  <pre class="lang-cs prettyprint-override"><code>private class MyExample
  {
      [Required]
      public string RequiredFieldTest { get; set; }
  
      [StringLength(100)]
      public int StringLengthFieldTest { get; set; }
  
      [Range(1, 100)]
      public int RangeFieldTest { get; set; }
  
      [DataType(DataType.Text)]
      public object DataTypeFieldTest { get; set; }
  
      [MaxLength(10)]
      public string MaxLengthFieldTest { get; set; }
  }
  </code></pre>
  <p>Then (pseudo) do something like this:</p>
  <pre class="lang-cs prettyprint-override"><code>var item = new MyExample(); // not setting any properties, should fail validation
  var isValid = item.Validate();
  </code></pre>
  <p>I found this code in a sample online:</p>
  <pre class="lang-cs prettyprint-override"><code>var item = new MyExample(); // not setting any properties, should fail validation
  
  var context = new ValidationContext(item, serviceProvider: null, items: null);
  var errorResults = new List&lt;ValidationResult&gt;();
  
  // carry out validation.
  var isValid = Validator.TryValidateObject(item, context, errorResults);
  
  // isValid will be FALSE
  </code></pre>
  <p>Which gives me &quot;isValid = false&quot; BUT it only seems to uphold the <code>Required</code> field and ignores the others.</p>
  <p>The following code returns <code>isValid = true</code> when I expect it to return <code>false</code>:</p>
  <pre class="lang-cs prettyprint-override"><code>var item = new MyExample() {
      RequiredFieldTest = &quot;example text&quot;
  };
  
  var context = new ValidationContext(item, serviceProvider: null, items: null);
  var errorResults = new List&lt;ValidationResult&gt;();
  
  // carry out validation.
  var isValid = Validator.TryValidateObject(item, context, errorResults);
  
  // isValid will be TRUE - not expected behavior
  </code></pre>
  <p>All other validation attempts using attributes (string length, range, max length, datatype etc) all pass as valid.</p>
  <p>Has anyone seen this behaviour before or know why it's happening?</p>