I have a validation class:
public sealed class ValidationSet : ValidationAttribute
{
private List<string> _set = new List<string>();
public ValidationSet(params string[] setOfValues)
{
_set = setOfValues.ToList();
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (!(_set.Select(s => s.ToLower()).Contains(value.ToString().ToLower())))
{
throw new Exception("not in the set");
}
return ValidationResult.Success;
}
}
and here is how I use it:
public class Car
{
[ValidationSet("honda", "gm")]
public string CarMake{ get; set; }
}
When I instantiate the Car class by:
...
Car c = new Car();
c.CarMake = "ford";
...
Nothing will happen and if I print c.CarMake, it shows ford - the validation didn't happened.
I am just wondering what do I miss here.
Thanks!
Just instantiating the class and assigning the field is not going to call IsValid, you need to use the class in a framework that examines Car, sees that it has ValidationAttribute on CarMake and will call IsValid.
In this example asp:DynamicValidator is doing the work: