Search code examples
angularformbuilder

Inclusion of regex based validator for formBuilder breaks checks in Angular 5.29


So here is the stackblitz:

https://stackblitz.com/edit/ionic-f9kfnm

Basically if formBuilder code in the constructor looks like this (excludes regex pattern):

this.signupForm = this.formBuilder.group({
      nickname: ['', Validators.compose([Validators.minLength(3), Validators.maxLength(20), Validators.required])],
      email: ['', Validators.compose([Validators.email, Validators.required])],
      password: ['', Validators.compose([Validators.minLength(3), Validators.maxLength(20), Validators.required])],
      ageTermsAccepted: [false, Validators.pattern('true')],
      policiesAccepted: [false, Validators.pattern('true')]
    });

The user experience with nickname checking looks fine (warning shows up and goes away only when input value is not valid.

Now if I add regex Validator:

this.signupForm = this.formBuilder.group({
      nickname: ['', Validators.compose([Validators.pattern('^[a-zA-Z0-9_-]$'),Validators.minLength(3), Validators.maxLength(20), Validators.required])],
      email: ['', Validators.compose([Validators.email, Validators.required])],
      password: ['', Validators.compose([Validators.minLength(3), Validators.maxLength(20), Validators.required])],
      ageTermsAccepted: [false, Validators.pattern('true')],
      policiesAccepted: [false, Validators.pattern('true')]
    });

The check is not working as expected.

Is there a rule that if I use regex I then have to only rely on it and can not combine this with other in build validators like max chars?


Solution

  • Your regex is missing quantifier, so it only accepts single character.

    '^[a-zA-Z0-9_-]*$'

    or you can specify min and max number of characters and you can drop minLength and maxLength validators (unless you want different validation messages):

    '^[a-zA-Z0-9_-]{3,20}$'