问题
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!
回答1:
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:
How to: Customize Data Field Validation
回答2:
I would look into FluentValidation. You can create a validator class for Car.
public class CarValidator : AbstractValidator<Car>
{
public CarValidator() {
RuleFor(m => m.CarMake).Equal("gm").Equal("honda");
}
}
Usage:
var car = new Car { CarMake = "honda" };
var validator = new CarValidator();
if (validator.Validate(car).IsValid)
// car is valid
来源:https://stackoverflow.com/questions/22567511/c-sharp-unable-to-validate-property-using-a-custom-validate-attribute