验证不会触发(System.ComponentModel.DataAnnotations)

时间:2015-05-27 13:58:19

标签: c# validation attributes system.componentmodel

我这里有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]

我的错误在哪里?

1 个答案:

答案 0 :(得分:1)

使用另一个重载:

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如果为false,则仅验证所需的属性..

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