C#无法使用自定义验证属性来验证属性 [英] C# Unable to validate property using a custom validate attribute

查看:101
本文介绍了C#无法使用自定义验证属性来验证属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个验证类:

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;
    }
}

这是我的用法:

public class Car
{
    [ValidationSet("honda", "gm")]
    public string CarMake{ get; set; }

}

当我通过以下方式实例化Car类时:

When I instantiate the Car class by:

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

什么都不会发生,如果我打印c.CarMake,它会显示福特-验证没有发生。

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.

谢谢!

推荐答案

仅实例化该类并分配该字段不会调用IsValid,您需要在检查Car的框架中使用该类,看看它是否具有ValidationAttribute

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.

在此示例中,asp:DynamicValidator正在执行此工作:

In this example asp:DynamicValidator is doing the work:

如何:自定义数据字段验证

这篇关于C#无法使用自定义验证属性来验证属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆