Reputation: 3851
This is my model with property OldPassword
[Required]
[StringLength(16, ErrorMessage = "The Old Password must be at least 8 characters long.", MinimumLength = 8)]
[RegularExpression("^(?=.*[a-z])(?=.*[A-Z]).+$", ErrorMessage = "Old Password is Not a valid Password")]
[Display(Name = "Old Password")]
public string OldPassword { get; set; }
And this is the rendered output
<input class="inputsmall defaultFocus input-validation-error" data-val="true"
data-val-length="The Old Password must be at least 8 characters long."
data-val-length-max="16" data-val-length-min="8"
data-val-regex="Old Password is Not a valid Password"
data-val-regex-pattern="^(?=.*[a-z])(?=.*[A-Z]).+$"
data-val-required="The Old Password field is required." id="OldPassword" maxlength="16" name="OldPassword" style="width: 295px;" type="password">
Current order of validation firing is
I would like to change the order to
I Googled a lot and couldn't find any straight forward solution. Please help me with this.
Upvotes: 6
Views: 2127
Reputation: 940
I tried the solution Jani gave, but it does not compile because GetValidator is sealed.
If you encounter such a case with multiple & ordered validations, instead of bending the framework, you should simply create your own custom validation attribute.
With namedparameters, you could end up with a very handy custom validationsomething that would look like :
[NameValidation(isRequired: true, requiredErrorMessage: "Merci de renseigner votre nom.",
malformedErrorMessage: "Votre nom n'est pas valide.", minLength: 1, maxLength: 100)]
Upvotes: 0
Reputation: 5407
You could create a custom class which inherits from DataAnnotationsModelValidatorProvider and override the GetValidators methods in it and register it as your ModelValidator. In the overriden methods you could sort the validators as you like.
public class OrderedAnnotationsModelValidatorProvider : DataAnnotationsModelValidatorProvider
{
public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)
{
return base.GetValidators(metadata, context).OrderBy(v => v.SomeProperty).AsEnumerable();
}
}
To use your OrderedAnnotationsModelValidatorProvider
you have to register it to the ModelValidatorProvidersCollection of ModelValidatorProviders in Global.asax.cs.
ModelValidatorProviders.Providers.Add(new OrderedAnnotationsModelValidatorProvider());
Upvotes: 9