编程语言
首页 > 编程语言> > c# – 如何根据DataAnnotation中的另一个属性验证属性

c# – 如何根据DataAnnotation中的另一个属性验证属性

作者:互联网

考虑一下我有这两个属性:

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并为IsOld选择“是”时,我返回一个正确的Age或IsOld的异常.我已经使用了CustomValidation,但因为我的验证必须是静态的,所以我无法访问其他属性.我如何通过DataAnnotation执行此操作?

解决方法:

您可以向类本身添加数据注释(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;
        }
    }
}

标签:c,c-4-0,data-annotations
来源: https://codeday.me/bug/20190613/1235126.html