我想创建一个自定义通用验证器,它将通过参数传递正则表达式的模式和要检查的属性(表单组)的名称。我有以下代码
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 }
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是当表达式无效时,返回"{propertyName: true}",而不是"{UserName: true}",有什么问题?
创建一个临时对象,然后返回。这里propertyNameinreturn { 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17615 次 |
| 最近记录: |