0
votes

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?

1
There's no such rule, you can mix whatever validators you want. I have checked your demo and it looks fine, what exactly is not working as expected? - Ludevik
current code there in the nickname (first) field gives you warning and the warning is not going away even if you typed in 4 characters (when field would be valid). Now if you go into the code and delete regex validator - you will see that warning shows up when you type in 1-2 characters, but then disappears the moment you get 3 characters typed in. I found that I only leave regex and remove in build validators - I can get what I want. but this is weird. - Sergey Rudenko

1 Answers

0
votes

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}$'