Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom ValidatorFn - Angular 6

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?

like image 710
avechuche Avatar asked Jun 03 '18 18:06

avechuche


2 Answers

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;
          }
        }
      }
like image 123
Amit Chigadani Avatar answered Oct 24 '22 01:10

Amit Chigadani


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 };
like image 28
Guerric P Avatar answered Oct 23 '22 23:10

Guerric P