Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to validate a property according to another property in DataAnnotation

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?

like image 473
Arian Avatar asked Nov 27 '11 06:11

Arian


1 Answers

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;
        }
    }
}
like image 102
Gary.S Avatar answered Sep 29 '22 07:09

Gary.S