这是我的属性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; }
这是渲染的输出
<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">
验证当前的验证顺序是
>必填
>正则表达式
>长度
我想将订单更改为
>必填
>长度
>正则表达式
解决方法
您可以创建一个继承自DataAnnotationsModelValidatorProvider的自定义类,并覆盖其中的GetValidators方法并将其注册为ModelValidator.在重写方法中,您可以根据需要对验证器进行排序.
public class OrderedAnnotationsModelValidatorProvider : DataAnnotationsModelValidatorProvider { public override IEnumerable<ModelValidator> GetValidators(ModelMetadata Metadata,ControllerContext context) { return base.GetValidators(Metadata,context).OrderBy(v => v.someProperty).AsEnumerable(); } }
要使用OrderedAnnotationsModelValidatorProvider,您必须将它注册到Global.asax.cs中的ModelValidatorProviders的ModelValidatorProvidersCollection.
ModelValidatorProviders.Providers.Add(new OrderedAnnotationsModelValidatorProvider());