user1740381
user1740381

Reputation: 2199

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?

Upvotes: 1

Views: 2741

Answers (2)

Tallmaris
Tallmaris

Reputation: 7590

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.

Upvotes: 1

Bhushan Firake
Bhushan Firake

Reputation: 9448

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.

Upvotes: 0

Related Questions