使用数据注释进行验证

时间:2016-01-09 07:05:11

标签: c# validation c#-4.0 data-annotations

基于这篇文章:Manual Validation with Data Annotations

我写这段代码:

public class Person04
{
    [CustomValidation(typeof(AWValidation), "ValidateSalesAmount")]
    public int SalesAmout { get; set; }

    [DataType(DataType.EmailAddress, ErrorMessage = "Invalid E-mail")]
    public string EmailAddress { get; set; }

    [Range(0, 99, ErrorMessage = "Age should be in range 0 to 99")]
    public int Age { get; set; }

    [Required(ErrorMessage="Name is required")]
    public string Name { get; set; }

    [StringLength(10, ErrorMessage = "Invalid Last Name")]
    public string LastName { get; set; }
}

public class AWValidation
{
    public static ValidationResult ValidateSalesAmount(int salesAmount)
    {
        if (salesAmount < 0)
        {
            return new ValidationResult("Invalid Sales Amount");
        }

        return ValidationResult.Success;
    }
}

 var person = new Person04() { SalesAmout = -1, Age = 100, EmailAddress = "nima", LastName = "Arian The Great" };
 var context = new ValidationContext(person, serviceProvider: null, items: null);
 var results = new List<ValidationResult>();

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

 if (!isValid)
 {
     foreach (var validationResult in results)
     {
         Console.WriteLine(validationResult.ErrorMessage);
     }
 }

但是这段代码只写了1个错误:

  

名称是必需的

为什么没有指定其他错误?

感谢

2 个答案:

答案 0 :(得分:4)

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

您缺少最后一个布尔参数,表示您希望验证所有属性:

  

validateAllProperties :true表示验证所有属性;如果为false,则仅验证所需的属性。

答案 1 :(得分:-1)

我想我找到了解决方案。你只是错过了一个ValidationContext类的对象。

          public class AWValidation
            {
                    public static ValidationResult ValidateSalesAmount(int salesAmount,ValidationContext validationContext)
                     {
                       if (salesAmount < 0)
                          {
                           return new ValidationResult("Invalid Sales Amount");
                          }

                      return ValidationResult.Success;
                     }
           }