如何根据Data Annotation中的另一个属性验证属性

时间:2011-11-27 06:10:32

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

考虑我有这两个属性:

public class Test
{
    [Required(ErrorMessage = "Please Enetr Age")]
    public System.Int32 Age { get; set; }
    [Required(ErrorMessage = "Choose an option")]
    public System.Boolean IsOld { get; set; }
}

当用户为Age输入例如15并为Yes选择“IsOld”时,我会返回更正AgeIsOld的异常。我已经使用了CustomValidation,但因为我的验证必须是静态的,所以我无法访问其他属性。我如何通过DataAnnotation

执行此操作

1 个答案:

答案 0 :(得分:7)

您可以向类本身添加数据注释(Custom Validator)。在验证属性的isValid方法中,您应该能够转换对象并测试需要满足的值。

示例:

using System;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // setup test object
            Test t = new Test() { Age = 16, IsOld = true };
            // store validation results
            Collection<ValidationResult> validationResults = new Collection<ValidationResult>();
            // run validation
            if (Validator.TryValidateObject(t, new ValidationContext(t, null, null), validationResults, true))
            {
                // validation passed
                Console.WriteLine("All items passed validation");
            }
            else
            {
                // validation failed
                foreach (var item in validationResults)
                {
                    Console.WriteLine(item.ErrorMessage);
                }
            }
            Console.ReadKey(true);
        }
    }

    [TestValidation(ErrorMessage = "Test object is not valid")]
    public class Test
    {
        public int Age { get; set; }
        public bool IsOld { get; set; }
    }

    public class TestValidation : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            bool isValid = false;
            Test testVal = value as Test;
            if (testVal != null)
            {
                // conditional logic here
                if ((testVal.Age >= 21 && testVal.IsOld) || (testVal.Age < 21 && !testVal.IsOld))
                {
                    // condition passed
                    isValid = true;
                }
            }
            return isValid;
        }
    }
}