Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validator.TryValidateObject Not Validating RangeAttribute

Given the following object,

public class Question {     [Required]     public string QuestionText { get; set; }      [Range(1, 5)]     public int Difficulty { get; set; }         } 

With the following Validation Code

ICollection<ValidationResult> results = new List<ValidationResult>(); Question question = new Question(); ValidationContext ctx = new ValidationContext(question, null, null); Validator.TryValidateObject(question, ctx, results); // results.Length = 1 

Why does Range attribute not create a validation error when Required does (the value is 0 obviously)?

like image 980
James Hughes Avatar asked Mar 20 '11 13:03

James Hughes


1 Answers

Ah so it would seem I need to specify validateAllProperties = true

Validator.TryValidateObject(question, ctx, results, true); 

Incidentally what was throwing me off was the fact I had an abstract base class with another property in it and without validateAllProperties the Validator will stop on the first error of ALL superclasses too. So you will get a validation error for each superclass (in my case 2)

like image 184
James Hughes Avatar answered Nov 15 '22 19:11

James Hughes