简体   繁体   English

单个属性上的多个自定义验证属性

[英]Multiple custom validation attribute on single property

I am working on a MVC 4 project. 我正在从事MVC 4项目。 I am having an issue with multiple custom validation attribute on single property. 我在单个属性上有多个自定义验证属性的问题。 Suppose I have 3 custom validation attribute for single property such as: 假设我有3个针对单个属性的自定义验证属性,例如:

public class Test
{
    [customAttribute1]
    [customAttribute2]
    [customAttribute3]
    public string property1 { get; set; }
}

Currently when I post he form than all three custom validations are performed on the property (no matter whether first validation pass or fail). 当前,当我发布他的表单时,将对属性执行所有三个自定义验证(无论第一次验证是通过还是失败)。

What I want is if customAttribute1 validation fails than no need to validate the property with next next custom attribute. 我想要的是,如果customAttribute1验证失败,那么无需使用下一个下一个自定义属性来验证该属性。 How can i achieve this? 我怎样才能做到这一点?

The point of this behaviour is to return back (to the UI) all the errors in the Model, so the user can fix all the errors at the same time... 此行为的重点是将模型中的所有错误返回(返回给UI),以便用户可以同时修复所有错误...

Let's say you want you password to be minimum 8 chars and have at least an uppercase and a number. 假设您希望密码最少8个字符,并且至少有一个大写字母和一个数字。 The way you want your validation to run is to stop if the password is not long enough without checking the rest. 您希望验证运行的方式是,如果密码不够长则停止而不检查其余密码。 Typical use case scenario: 典型的用例场景:

User sets password "foo" -> submit
error - Password too short
User sets it to "foofoofoo"
error - Password must have an uppercase
User sets it to "FooFooFoo"
error - Password must have a number
User goes away frustrated...

So, if the 3 attributes are to be validated together, my suggestion is to keep this behaviour. 因此,如果要一起验证这3个属性,我的建议是保留这种行为。 If the 3 are exclusive then do as others suggested and combine them into a single attribute. 如果3是排他性的,则按照其他建议进行操作,并将它们组合为单个属性。

Ordering or executing conditionally is not supported AFAIK. 不支持AFAIK有条件地排序或执行。

The best bet is to have all these 3 validations in the same attribute. 最好的选择是将所有这三个验证都放在同一个属性中。

If you are badly in need of this kind of validation, then Fluent Validation can do it for you. 如果您非常需要这种验证,那么Fluent Validation可以为您完成。

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

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