如果要对一个数据对象应用多个正则表达式验证以及客户端验证,则不能使用与“regex”相同的 ValidationType 名称。您需要以某种方式使用自己的自定义唯一 ValidationType。您的 javascript 部分的问题是您为正则表达式验证器方法使用了错误的注入方法。
$.validator.unobtrusive.adapters.addBool('regularexpression');
您需要使用下面的方法而不是上面的方法,以便将服务器端模式值传递给客户端方法
$.validator.unobtrusive.adapters.addSingleVal("regularexpression", "pattern");
这是我的示例源...
在服务器端,创建每个自定义验证属性。
public class OneDigitAttribute : RegularExpressionAttribute, IClientValidatable
{
public OneDigitAttribute()
: base(@"^.*(?=.*\d).+$")
{
ErrorMessage = "Required at least one numeric digit";
}
// for supporting a client-side validation through jquery.validation.unobtrusive
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRegexRule(this.ErrorMessage, this.Pattern)
{
ValidationType = "onedigit"
};
}
}
public class OneAlphaAttribute : RegularExpressionAttribute, IClientValidatable
{
public OneAlphaAttribute()
: base(@"^.*(?=.*[a-zA-Z]).+$")
{
ErrorMessage = "Required at least one alphabet character";
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRegexRule(this.ErrorMessage, this.Pattern)
{
ValidationType = "onealpha"
};
}
}
public class OneSpecialCharacterAttribute : RegularExpressionAttribute, IClientValidatable
{
public OneSpecialCharacterAttribute()
: base(@"^.*(?=.*[^a-zA-Z0-9]).+$")
{
ErrorMessage = "Required at least one non alphabet numeric(special) character";
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRegexRule(this.ErrorMessage, this.Pattern)
{
ValidationType = "onespecial"
};
}
}
并将它们应用于相同的属性
[OneDigit]
[OneAlpha]
[OneSpecialCharacter]
[DataType(DataType.Password)]
public string NewPassword { get; set; }
...
然后,在客户端添加每个唯一的验证方法,如下所示
$.validator.addMethod("onedigit", function (value, element, regexp) {
var re = new RegExp(regexp); return re.test(value);
});
$.validator.addMethod("onealpha", function (value, element, regexp) {
var re = new RegExp(regexp); return re.test(value);
});
$.validator.addMethod("onespecial", function (value, element, regexp) {
var re = new RegExp(regexp); return re.test(value);
});
jQuery.validator.unobtrusive.adapters.addSingleVal("onedigit", "pattern");
jQuery.validator.unobtrusive.adapters.addSingleVal('onealpha', "pattern");
jQuery.validator.unobtrusive.adapters.addSingleVal('onespecial', "pattern");
请确保不要将它们全部放在 DOM 就绪函数中。例如:
/* $(function() { */
$.validator.addMethod("regularexpression", function (value, element, regexp) {
var re = new RegExp(regexp); return re.test(value);
});
$.validator.unobtrusive.adapters.addSingleVal("regularexpression", "pattern");
/* }); */