我想创建一个自定义通用验证器,它将通过参数传递正则表达式的模式和要检查的属性(表单组)的名称。我有以下代码
UserName: new FormControl('',
[
Validators.required,
Validators.minLength(8),
this.OnlyNumbersAndLetterValidator(/^[a-zA-Z0-9]+$/, "UserName")
]
)
OnlyNumbersAndLetterValidator(regexPattern: RegExp, propertyName: string): ValidatorFn {
return (currentControl: AbstractControl): { [key: string]: any } => {
if (!regexPattern.test(currentControl.value)) {
return { propertyName: true }
}
}
}
问题是当表达式无效时,返回 "{propertyName: true}" , 而不是 “{用户名:true}” , 问题是什么?
最佳答案
创建一个临时对象,然后返回。这里propertyName
在 return { propertyName: true }
是一个字符串而不是输入变量。
OnlyNumbersAndLetterValidator(regexPattern: RegExp, propertyName: string): ValidatorFn {
return (currentControl: AbstractControl): { [key: string]: any } => {
if (!regexPattern.test(currentControl.value)) {
let temp = {};
temp[propertyName] = true;
return temp;
}
}
}
关于angular - 自定义 ValidatorFn - Angular 6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50669872/