Why and I getting: “Invalid regular expression. Un

2020-02-02 03:44发布

问题:

Im trying to create an html input tag that accepts only numbers entered in 1 of 2 formats, and reject all other input.

I want to accept numbers in these formats only, including requiring the dashes:

1234-12

and

1234-12-12

note: this is not for dates, but rather legal chapter numbers

Everything I am reading about regex says that the following should work, but it isn't.

<input class="form-control"
                       type="text"
                       pattern="^(\d{4}\-\d{2}\-\d{2})|(\d{4}\-\d{2})$"
                       required />

Devtools Console Error in Chrome:

Pattern attribute value ^(\d{4}\-\d{2}\-\d{2})|(\d{4}\-\d{2})$ is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /^(\d{4}-\d{2}-\d{2})|(\d{4}-\d{2})$/: Invalid escape

回答1:

You should not escape the hyphen outside a character class in ES6 regex used with the u flag (the one used by default in pattern regexps in the current versions of Chrome and FF).

Also, the regex in the pattern attribute is anchored by default, remove the redudant ^ and $ and shorten the pattern by using an optional group

pattern="\d{4}-\d{2}(-\d{2})?"

This regex in the HTML5 pattern attribute means:

  • \d{4}-\d{2} - match 4 digits, -, and then 2 digits from the start of string
  • (-\d{2})? - and optionally match a - and then 2 digits at the end of the string.