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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With