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
?
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With