how to validate a property according to another property in DataAnnotation

笑着哭i 提交于 2020-01-02 05:32:09

问题


Consider I have a these two properties:

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; }
}

When the user enters for example 15 for Age and choose "Yes" for IsOld, I return an exception that correct Age or IsOld. I've used CustomValidation for it, but because my my validation must be static I can't access to other properties. How can I do this by a DataAnnotation?


回答1:


You can add data annotations (Custom Validator) to the class itself. In the isValid method of your validation attribute you should then be able to cast the object and test the values that need to be fulfilled.

Example:

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;
        }
    }
}


来源:https://stackoverflow.com/questions/8283968/how-to-validate-a-property-according-to-another-property-in-dataannotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!