1

Regex pattern ^(\+?6?01)[0|1|2|3|4|6|7|8|9]\-*[0-9]{7,8}$ in HTML5 input return error. I tested the regex, no errors on regex101.com as well as in my php code. But in HTML5 it does not function as it be. My code:

<input class="mdl-textfield__input" name="mobile_number" type="text" pattern="^(\+?6?01)[0|1|2|3|4|6|7|8|9]\-*[0-9]{7,8}$">

Error:

textfield.js:146 Pattern attribute value ^(+?6?01)[0|1|2|3|4|6|7|8|9]-*[0-9]{7,8}$ is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /^(+?6?01)[0|1|2|3|4|6|7|8|9]-*[0-9]{7,8}$/: Invalid escape

Anyone can help me? Thanks in advance for any helps offered.

My tested regex: https://regex101.com/r/1WsVwo/1

Nere
  • 3,919
  • 4
  • 24
  • 62

3 Answers3

4

You have a few problems with your regex. The one causing the "invalid escape" error is that you have \-, but you do not need to (and should not) escape the hyphen. You should just have -. A proper version of your input is:

<input class="mdl-textfield__input" name="mobile_number" type="text" pattern="^(\+?6?01)[0-46-9]-*[0-9]{7,8}$">

Here's a demo.

In that example, I've also replaced the group [0|1|2|3|4|6|7|8|9] with the cleaner and more accurate [0-46-9]. In a character group (like [...]), the pipe symbol (|) is just another character, with no special meaning. So, for example, [0|1] doesn't just match 0 or 1; it also matches a literal | character, which is not what you wanted. You might find this post helpful: Reference - What does this regex mean?

elixenide
  • 42,388
  • 14
  • 70
  • 93
-1

because your syntax error, invalid escape - => -

this correct:

<input class="mdl-textfield__input" name="mobile_number" type="text" pattern="^(\+?6?01)[0|1|2|3|4|6|7|8|9]-*[0-9]{7,8}$">
-1

<input class="mdl-textfield__input" name="mobile_number" type="text" pattern="(\+?6?01)[0-9]{7,8}">

i change your pattern to (\+?6?01)[0-9]{7,8}

*Update: (\+?6?01)[0-46-9]-*[0-9]{7,8}

See demo

Truong Cong Hau
  • 143
  • 1
  • 6