I inject some Regex string to input element's pattern attribute via javascript (depending on some form changes out of context) and it works as expected but the thing is, it logs an error to the console when I focus on the input for the very first time.
I've tried to escape the regex as you can see below but then HTML input failed to validate the corresponding value according to the pattern used before.
required regex code
(\(?([\d \-\)\–\+\/\(]+){6,}\)?([ .\-–\/]?)([\d]+))
and that's how i define and inject it via JS
/([\d \-\)\–\+\/\(]+){6,}\)?([ .\-–\/]?)([\d]+)/g
and here's what I tried and failed while trying to escape it for HTML pattern attribute
([\d \-)–+/(]+){6,}\)?([.-–/]?)([\d]+)
I'm really seeking a way to achieve all these without any errors:
- regex will be used in JS to
matchwith the input value and only proceed if it's valid - it will also be used in HTML as a pattern attribute to give user feedback about input validation hopefully without any errors like this one;
Pattern attribute value /(\(?([\d \-\)\–\+\/\(]+){6,}\)?([ .\-–\/]?)([\d]+))/g is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: //(\(?([\d \-\)\–\+\/\(]+){6,}\)?([ .\-–\/]?)([\d]+))/g/: Invalid escape
([\d \-\)\–\+\/\(]+){6,}makes no sense. You match one or more chars in the char class 6 or more times. What should the pattern match?^your_pattern$, add anchors./^\(?[\d +\/()–-]{6,}\)?[ .\/–-]?\d+$/inString#matchandpattern="\(?[\d +\/()–-]{6,}\)?[ .\/–-]?\d+"