web-dev-qa-db-ja.com

カスタム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 }
          }
        }
      }

問題は、式が無効な場合、"{UserName:true}"の代わりに"{propertyName:true}"を返すことです。問題は何ですか?

3
avechuche

一時オブジェクトを作成してから戻ります。ここで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;
          }
        }
      }
1
Amit Chigadani

{ propertyName: true }を返しています。これは、propertyNameという名前のプロパティを持つオブジェクトを意味します。

あなたがしたいことは:

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