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

编程入门 行业动态 更新时间:2024-10-21 12:52:29
本文介绍了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#无法使用自定义验证属性来验证属性

本文发布于:2023-10-27 03:09:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1532137.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   自定义

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!