我正在使用自定义验证器函数,该函数使用RegEx来确定匹配项。
newPassword: [
null,
Validators.compose([
Validators.required,
// check whether the entered password has a number
CustomValidators.patternValidator(/\d/, {
hasNumber: true
}),
// check whether the entered password has upper case letter
CustomValidators.patternValidator(/[A-Z]/, {
hasCapitalCase: true
}),
// check whether the entered password has a lower case letter
CustomValidators.patternValidator(/[a-z]/, {
hasSmallCase: true
}),
// check whether the entered password has a special character
CustomValidators.patternValidator(
/[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/,
{
hasSpecialCharacters: false
}
),
Validators.minLength(8)
])
]
函数看起来像这样
export class CustomValidators {
static patternValidator(regex: RegExp, error: ValidationErrors): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
if (!control.value) {
// if control is empty return no error
return null;
}
// test the value of the control against the regexp supplied
const valid = regex.test(control.value);
// if true, return no error (no error), else return error passed in the second parameter
return valid ? null : error;
};
}
我的问题是我该如何增强它,例如要求2个大写字母,因为我的功能仅检查是否存在大写字母。
答案 0 :(得分:1)
您需要在正则表达式中添加一个量词。量词{2,}
表示它必须至少匹配两次
CustomValidators.patternValidator(/[A-Z]{2,}/, {
hasCapitalCase: true
}),