简体   繁体   中英

Angular2 model-driven form validator pattern

I'm trying to make a form valid only if it matches a certain pattern.

It must match:

123456789
123-456-789
123 458 789

Here is my pattern:

^(\d{3}-\d{3}-\d{3})|(\d{3} \d{3} \d{3})|(\d{9})$

First, fun fact, to be able to use it on Validator, it seems i've to escape every slash in it.

Validators.pattern('^(\\d{3}-\\d{3}-\\d{3})|(\\d{3} \\d{3} \\d{3})|(\\d{9})$')

And my problem is it doesn't restrict the total string size number.

For example, it matches 1234567890000, i would like it to stop at 123456789 and any additional character would trigger the false state.

I tried these variants:

Validators.pattern('^(\\d{3}-\\d{3}-\\d{3})|(\\d{3} \\d{3} \\d{3})|(\\d{9})$')
Validators.pattern('(\\d{3}-\\d{3}-\\d{3})|(\\d{3} \\d{3} \\d{3})|(\\d{9})')

Another fun fact, if I set it to:

Validators.pattern('\\d{9}')

or

Validators.pattern('^\\d{9}$')

Then i can only set exactly 9 characters.

I'm sure it's a regex error, but i don't understand if Angular2 requires to give him ^ and $ symbols to delimit the string to be evaluated.

You must use double backslashes because the pattern is passed to the regex engine as a string literal, and regex escaping requires literal backslashes with \\d , \\w , etc.

From what I see from my testing, angular adds ^ and $ anchors around the pattern without grouping it.

That means, when you have alternation groups, wrap them with a grouping construct so that the anchors could be applied to all the alternatives.

Your ^(\\\\d{3}-\\\\d{3}-\\\\d{3})|(\\\\d{3} \\\\d{3} \\\\d{3})|(\\\\d{9})$ and other attemped patterns contain unwrapped alternatives, so ^ only applies to (\\\\d{3}-\\\\d{3}-\\\\d{3}) and $ only applies to (\\\\d{9}) .

Use

'(?:\\d{3}([- ])\\d{3}\\1\\d{3}|\\d{9})'

Inside the validator code, it will appear as ^(?:\\\\d{3}([- ])\\\\d{3}\\\\1\\\\d{3}|\\\\d{9})$ , and will work like in this demo .

Details : the pattern will match 2 alternatives:

  • \\\\d{3}([- ])\\\\d{3}\\\\1\\\\d{3} - 3 digits, - or space (captured into Group 1), then 3 digits, then the same separator as in Group 1, and then 3 digits
  • | - or
  • \\\\d{9} - 9 digits

Since the ^ and $ are added by angular, the patterns will require full string match.

设置Validator.maxLength将不允许用户键入超过给定长度的字符。

new FormControl('', Validators.maxLength(9)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM