Search code examples
asp.net-mvc-4client-side-validationvalidation

Change order of validation triggering in asp.net mvc 4 model


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

  • required
  • regex
  • length

I would like to change the order to

  • required
  • length
  • regex

I Googled a lot and couldn't find any straight forward solution. Please help me with this.


Solution

  • 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());