我想要创建一个定制的泛型验证器,它将通过参数传递要检查的正则表达式的模式和属性( will组)的名称。我有以下代码
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}",而不是"{UserName: true}",问题是什么?
发布于 2018-06-03 18:58:53
创建一个临时对象,然后返回。这里,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;
}
}
}发布于 2018-06-03 19:00:07
返回{ propertyName: true },这意味着具有名为propertyName的属性的对象
你想做的是:
let returnValue = {};
returnValue[propertyName] = true;
return returnValue;甚至更短:
return { [propertyName]: true };https://stackoverflow.com/questions/50669872
复制相似问题