我有一张注册表,并实现了一些我想在客户端进行验证的密码验证属性。
这是验证属性之一的代码:
public sealed class ContainsUpperAndLowerCaseAttribute : RegularExpressionAttribute, IClientValidatable
{
private const string _pattern = @"^(?=.*[a-z])(?=.*[A-Z])[A-Za-z\d$@$!%*?&]*";
public ContainsUpperAndLowerCaseAttribute() : base(_pattern)
{
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule()
{
ValidationType = "upperlower",
ErrorMessage = ErrorMessage
};
rule.ValidationParameters.Add("pattern", _pattern);
yield return rule;
}
}
我有两个具有相同正则表达式和ValidationType
属性的相同属性。
视图模型的代码为:
public class RegisterViewModel
{
[Required(ErrorMessage = "This field is required")]
[EmailAddress]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[DataType(DataType.Password)]
[Required(ErrorMessage = "This field is required")]
[StringLength(100, ErrorMessage = "Should be at least 8 characters", MinimumLength = 8)]
[ContainsDigits(ErrorMessage = "Password should contain digits")]
[ContainsUpperAndLowerCase(ErrorMessage = "Password should contain upper and lower case characters"))]
[ContainsNonLeterAndDigitSymbol(ErrorMessage = "Password should contain non letter and non digit characters")]
public string Password { get; set; }
}
然后我将这些规则应用于JS中的表单:
$.validator.addMethod("upperlower", function (value, element, regexp) {
var re = new RegExp(regexp); return re.test(value);
});
$.validator.addMethod("digits", function (value, element, regexp) {
var re = new RegExp(regexp); return re.test(value);
});
$.validator.addMethod("symbols", function (value, element, regexp) {
var re = new RegExp(regexp); return re.test(value);
});
jQuery.validator.unobtrusive.adapters.addSingleVal("digits", "pattern");
jQuery.validator.unobtrusive.adapters.addSingleVal('upperlower', "pattern");
jQuery.validator.unobtrusive.adapters.addSingleVal('symbols', "pattern");
但是,当我测试此代码时,UI中仅显示一个验证错误,并在控制台中使用以下命令进行检查:console.log($('#form').validate().errorList)
-它仅包含一个错误。我确信所有验证属性都可以正常工作,因为它们显示为一个一个,如:如果我键入不带数字的密码,则表明我应该添加数字,然后表明我应该添加大写字符,但我想显示所有错误。同时。
如果可以的话,请给我建议实施这样的事情?
谢谢您的帮助