正規表現のパターンとチェックする(フォームグループの)プロパティの名前をパラメーターで渡すカスタムジェネリックバリデーターを作成したいと思います。私は次のコードを持っています
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}"を返すことです。問題は何ですか?
一時オブジェクトを作成してから戻ります。ここで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;