2

When I use this regex declaration in javascript:

var phoneRegExp = /^(\+\s?)?((?<!\+.*)\(\+?\d+([\s\-\.]?\d+)?\)|\d+)([\s\-\.]?(\(\d+([\s\-\.]?\d+)?\)|\d+))*(\s?(x|ext\.?)\s?\d+)?$/i;

it gives me an "Unexpected quantifier" error in IE10. Chrome reports an "Invalid group". As far as I can see the expression is ok, I have tested it with http://regexhero.net/tester and it is the same as is used in the .NET4.5 PhoneAttribute

Any ideas?

Jaap
  • 2,252
  • 2
  • 20
  • 24
  • 7
    Javascript RegExp does not support look-behind assertions (`(?<!\+.*)`). – lanzz Sep 19 '12 at 11:48
  • @lanzz Can't you do this: http://stackoverflow.com/a/7376273/1240268. Please also see http://sscce.org/ – Andy Hayden Sep 19 '12 at 12:16
  • @hayden Probably, look-aheads are supported. I don't have the time to dig deeper into the regex to provide an alternative approach, and it is not really a trivial one, thus my comment instead of an answer. – lanzz Sep 19 '12 at 12:50
  • @lanzz I concur. Sorry I really meant that as a comment for the OP. – Andy Hayden Sep 19 '12 at 12:51

1 Answers1

2

Faced the same issue and solved it by reversing original regex pattern and replacing lookbehind with lookahead. The last trick is to reverse input string that is going to be tested against the regex.

This idea is well described in Steven Levithan's Mimicking Lookbehind in JavaScript blog post.

Below is my test page where you can see the working regex:

<html>
    <head>
        <title>Phone Number RegExp Test Page</title>
    </head>
    <body>
        <script>
            function validateInput() {              
                var phoneRegex = new RegExp("^(\\d+\\s?(x|\\.txe?)\\s?)?((\\)(\\d+[\\s\\-\\.]?)?\\d+\\(|\\d+)[\\s\\-\\.]?)*(\\)([\\s\\-\\.]?\\d+)?\\d+\\+?\\((?!\\+.*)|\\d+)(\\s?\\+)?$", "i");

                var input = document.getElementById("tbPhone");
                var value = input.value.split("").reverse().join("");
                alert(phoneRegex.test(value));
            }           
        </script>

        <input type="text" id="tbPhone" />
        <button onclick="javascript:testPhone()">Validate</button>
    </body>
</html>
Alexander Manekovskiy
  • 3,185
  • 1
  • 25
  • 34