Skill Test: Form Validation 2

Hi @CalinObo

That’s a great question. It took me some time but I could finally solve this riddle. :grin:

TL,DR: Remove the two backslashes in front of the hyphens, because unnecessary escapes cause the pattern to be ignored. For an explanation why this happens see below.

At first, this pattern looks like it should work. I used your regex in JS to confirm that:

const re = /[0-9]{10}|[0-9]{3}\.*\s*\-*[0-9]{3}\.*\s*\-*[0-9]{4}/;
const str = '111';
console.log(re.test(str)); /* false (as expected) */

This means there is a difference between a “normal” regex and the regex in pattern attributes. On <input type="text"> it’s explained that pattern sets the “u” flag (Unicode) on regexes.
When we use the Unicode flag in my example above (put a u after the last / in the regex) it indeed throws an error:

Uncaught SyntaxError: invalid identity escape in regular expression

So this is the reason why it gets ignored in the pattern. The question is why? We find the answer on the guide about regular expressions under “Using unicode regular expressions”:

Unicode regular expressions do not support so-called “identity escapes”; that is, patterns where an escaping backslash is not needed and effectively ignored. For example, /\a/ is a valid regular expression matching the letter ‘a’, but /\a/u is not.

The hyphen (-) doesn’t need to be escaped. In a regex without the “u” flag it’s ignored, but throws an error in a regex with the “u” flag. The solution: Remove the two backslashes in front of the hyphens.


I hope this little insight about how I find an explanation for something will help you in similar situations in the future. :slightly_smiling_face:

Have a nice day,
Michael

1 Like