43

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)?

2 Answers 2

79

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)

Sign up to request clarification or add additional context in comments.

6 Comments

The original post is nearly 3 years old, I'd expect some drift in behaviour.
Turned out my problem was slightly different - stackoverflow.com/questions/21111905/…
Still works for me 6 years later - behaviour hasn't drifted that much, and still a surprise to me that the default is false.
Goodness. I can't believe true isn't the default for this. What a headache. Thank you
I feel this is as appropriate of an API choice as having a method called ShouldExecuteCode. Thanks, I missed this.
|
23

Validator.TryValidatorObject(instance, validationContext, validationResults) calls Validator.TryValidateObject(instance, validationContext, validationResults, validateAllProperties) with validateAllProperties = false.

When validateAllProperties is false, only the RequiredAttribute will be validated.

2 Comments

My goodness what a mess is this. Hope Microsoft understand there is something called as the word "user friendly".
That is not intuitive at all. :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.