Rutger Cappendijk
Rutger Cappendijk

Reputation: 239

Angular (12.0.5) Formbuilder regex validation

I am trying to validate passwords, postal codes and phone numbers using the Angular pattern validators.

For some reason the password and postal code validation just don't seem to work, no matter which regex I try. The phone number regex works just fine though, which confuses me even more. I'm not sure where the error is, since even simple regex patterns don't seem to work, implying the error is in the formbuilder. However, it doesn't seem like I'm doing anything differently from the phone number regex.

Thanks in advance!

Regex used:

// Regex to check for valid phone number
phoneRegex = "^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*$";
// Minimum eight characters, at least one letter, one number and one special character:
passRegex = "^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$";
// Postalcode regex (intended effect: 4 numbers, followed by two letters)
PostalRegex = "^\d{4}[a-zA-Z]{2}";

Formbuilder (simplified to include only relevant formcontrols):

this.userForm = this.fb.group({
      phoneNumber: ['', {updateOn: 'blur', validators: [Validators.required, Validators.minLength(8), Validators.maxLength(12), Validators.pattern(this.phoneRegex)]}],
      password: ['', {updateOn: 'blur', validators: [Validators.required, Validators.minLength(8), Validators.maxLength(32), Validators.pattern(this.passRegex)]}],
      passwordConf: ['', {updateOn: 'blur', validators: Validators.required}],
      postalCode: ['', {updateOn: 'blur', validators: [Validators.required, Validators.pattern(this.PostalRegex)]}],
}, { updateOn: 'submit', validators: this.checkPassMatch.bind(this) } as AbstractControlOptions);
    }

Upvotes: 0

Views: 1032

Answers (1)

user776686
user776686

Reputation: 8675

Your PostalRegex will run just fine when you convert it from a string into a RegExp literal:

/^\d{4}[a-zA-Z]{2}/

Although API accepts both Regexp and string, when you pass a string, it forces ^ and $ on respective ends which might affect the results - docs.

If you want to have confidence over what pattern is used by Angular Validator, it would be recommendable that you convert all regexps this way.

Also, please note that the password regexp needs a backslash escape for digits, ie. d should be \d. Compare with this answer :)

Upvotes: 0

Related Questions