Using Angular Validators to create a restriction of 6-12 characters, but NOT of length 9

857 views Asked by At

I am trying to create a Angular Validator that allows me to validate a string of both letters and characters of lengths 6-12 inclusive, but not of length 9.

I have tried

RegexAlphaNumeric = "^[a-zA-Z0-9]{6,8}|[a-zA-Z0-9]{10,12}$";
userId: ['', [Validators.minLength(6), Validators.maxLength(12),Validators.pattern(this.RegexAlphaNumeric)],],

Wondering if my usage of minLength and maxLength should not be used here and if there is a way to just utilize Validators.pattern() for this method.

1

There are 1 answers

0
The fourth bird On

You could either use a negative lookahead to assert not 9 characters:

^(?![a-zA-Z0-9]{9}$)[a-zA-Z0-9]{6,12}$

See a regex101 demo.

Or use an alternation as you already have in your question, but you have to group the parts between the start and the end of the string or else the pattern would match either 6-8 chars from the start or 10-12 chars at the end only.

^(?:[a-zA-Z0-9]{6,8}|[a-zA-Z0-9]{10,12})$

See a regex101 demo.