title: Integer validation against non-required attributes in MVC
body: <p>I've trying to validate a property on a model I have. This property is NOT required, and so if its invalid MVC seems to be ignoring it. I've even created a custom ValidationAttribute, but nothing works. </p>
  
  <pre><code>public class NumberWang : ValidationAttribute
  {
      public override bool IsValid(object value)
      {
          if (value == null)
              return true;
  
          int g;
          if (int.TryParse(value.ToString(), out g))
          {
              if (g &gt;= 0)
                  return true;
          }
          return false;
      }
  }
  
  public class MyModel 
  {
      [Range(0, 999999, ErrorMessage = "category_id must be a valid number")]
      [NumberWang(ErrorMessage = "That's NumberWang!")]
      public int? category_id { get; set; }
  
      /* there are other properties of course, but I've omitted them for simplicity */
  
      public void Validate()
      {
          Validator.TryValidateProperty(this.category_id,
          new ValidationContext(this, null, null) { MemberName = "category_id" },
          this.validation_results);
      }
  }
  </code></pre>
  
  <p>If I pass the value 'abc' as a category_id to this model, it validates just fine. What am I doing wrong? </p>