I want to create a custom generic validator, which will pass by parameter the pattern of the regular expression and the name of the property (of a formgroup) to be checked. I have the following code
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 }
}
}
}
The problem is that when the expression is not valid, return "{propertyName: true}", instead of "{UserName: true}", what is the problem?
Create a temp object and then return. Here propertyName
in return { propertyName: true }
is a string and not the input variable.
OnlyNumbersAndLetterValidator(regexPattern: RegExp, propertyName: string): ValidatorFn {
return (currentControl: AbstractControl): { [key: string]: any } => {
if (!regexPattern.test(currentControl.value)) {
let temp = {};
temp[propertyName] = true;
return temp;
}
}
}
You are returning { propertyName: true }
which means an object with a property named propertyName
What you want to do is:
let returnValue = {};
returnValue[propertyName] = true;
return returnValue;
Or even shorter:
return { [propertyName]: true };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With