简体   繁体   中英

Multiple custom validation attribute on single property

I am working on a MVC 4 project. 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:

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. 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...

Let's say you want you password to be minimum 8 chars and have at least an uppercase and a number. 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. If the 3 are exclusive then do as others suggested and combine them into a single attribute.

Ordering or executing conditionally is not supported 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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