自定义 ValidatorFn - Angular 6

Custom ValidatorFn - Angular 6

我想创建一个自定义通用验证器,它将通过参数传递正则表达式的模式和要检查的 属性(表单组的)名称。我有以下代码

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 }
          }
        }
      }

问题是当表达式无效时,return "{属性Name: true}",而不是 "{UserName: true}",有什么问题?

创建一个临时对象,然后 return。这里 propertyName in 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;
          }
        }
      }

您正在返回 { propertyName: true },这意味着一个对象 属性 名为 propertyName

您想做的是:

let returnValue = {};
returnValue[propertyName] = true;
return returnValue;

或更短:

return { [propertyName]: true };