验证未触发 (System.ComponentModel.DataAnnotations)

Validation doesn't fire (System.ComponentModel.DataAnnotations)

我这里有这个 class,有 2 个属性 NameAge

using System.ComponentModel.DataAnnotations;
public class Person
{
    [Required(AllowEmptyStrings = false)]
    [StringLength(25, MinimumLength = 2)]
    [RegularExpression(@"^[a-zA-Z]+$")]
    public string Name { get; set; }
    [Range(0, 100)]
    public int Age { get; set; }
}

我尝试验证这些值

Person pTemp = new Person();
pTemp.Name = "x"; //invalid because length <2
pTemp.Age = 200; //invalid because > 100
//validation here 
var context = new ValidationContext(pTemp);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(pTemp, context, results);
results.ForEach(x => Console.WriteLine(x.ErrorMessage));

但唯一触发的验证属性是 [Required]

我哪里错了?

使用另一个重载:

var isValid = Validator.TryValidateObject(pTemp, context, results, true);

来自 MSDN:

public static bool TryValidateObject(
   Object instance,
   ValidationContext validationContext,
   ICollection<ValidationResult> validationResults,
   bool validateAllProperties
)

validateAllProperties 类型:System.Boolean true 验证所有属性;如果为假,则只验证必需的属性..

由于默认情况下 bool 等于 false,因此您只验证了 Required 个属性。