Validator.TryValidateObject Not Validating RangeAttribute

后端 未结 2 1038
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 18:24

Given the following object,

public class Question
{
    [Required]
    public string QuestionText { get; set; }

    [Range(1, 5)]
    public int Difficulty          


        
相关标签:
2条回答
  • 2020-12-29 18:59

    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.

    0 讨论(0)
  • 2020-12-29 19:17

    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)

    0 讨论(0)
提交回复
热议问题