简体   繁体   English

C#无法使用自定义验证属性来验证属性

[英]C# Unable to validate property using a custom validate attribute

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类时:

...
Car c = new Car();
c.CarMake = "ford";
...

Nothing will happen and if I print c.CarMake, it shows ford - the validation didn't happened. 什么都不会发生,如果我打印c.CarMake,则显示为福特-验证未发生。

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. 只需实例化该类并分配该字段就不会调用IsValid,您需要在检查Car,看到CarMake上具有ValidationAttribute并调用IsValid的框架中使用该类。

In this example asp:DynamicValidator is doing the work: 在此示例中,asp:DynamicValidator正在执行工作:

How to: Customize Data Field Validation 如何:自定义数据字段验证

I would look into FluentValidation. 我将研究FluentValidation。 You can create a validator class for Car. 您可以为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM