-1

I have a regex to validate phone numbers. It should allow only + , (, ) and - symbol in it. Right now everything works fine except for 2 issues. The regex should allow + symbol only at the beginning and not anywhere in the middle. the other symbols, ie: -, ( and ) symbols should not appear one after another.

regex used is as follows

/^(?=.*?[1-9])[0-9-()+ ]+$/

any suggestions to fix this would be helpful.

Gautam
  • 1,046
  • 5
  • 20
  • Remove `+` & `-` from character class and add them after `^` anchor inside character class. Follow it by `?` to make it optional. – Tushar Jan 05 '18 at 06:11
  • Can you show us some sample numbers which you are trying to match? – Tim Biegeleisen Jan 05 '18 at 06:12
  • Possible duplicate of [Validate phone number with JavaScript](https://stackoverflow.com/questions/4338267/validate-phone-number-with-javascript) – Tim Biegeleisen Jan 05 '18 at 06:13
  • To save you some time, the accepted answer on that question says: Don't use a regex, use a library, and [this](https://github.com/googlei18n/libphonenumber) is the library they linked. – user3483203 Jan 05 '18 at 06:20

2 Answers2

0

This code will only allow you to enter + and - at the beginning.

<!DOCTYPE html>
<html>
<head>
    <title>Modifiers</title>
</head>
<body>

    <input type="text" name="mob" id="demo">
    <input type="submit" name="submit" onclick="myfunc()">

    <script type="text/javascript">

function myfunc(){
    var movV= document.getElementById('demo').value; 
    var mob = movV.replace(/[?:+ | ?:-]\d/, '');
    if (mob != movV) {
        alert("true");
    } 
    else if (mob == movV) {
        alert("false");
    }
}
    </script>
</body>
</html>
Nikhil Savaliya
  • 2,138
  • 4
  • 24
  • 45
0

As you state that right now everything works fine except for 2 issues, you could allow an optional plus sign at the beginning of the string:

\+?

If you mean by

"the other symbols, ie: -, ( and ) symbols should not appear one after another"

that (( or ))) or ---- should not happen, then you could use lookarounds to assert that the -, ( and ) symbols should not appear one after another:

(?!.*([-()])(?=\1))

Explanation

  • A negative lookahead (?!
  • Which asserts that what follows .*
  • Capture in a group the possible symbols ([-()])
  • A positive lookahead (?=
  • Which asserts that what follows is what is captured in group 1 \1
  • Close the positive lookahead )
  • Close the negative lookahead )

Your regex would then look like:

^\+?(?!.*([-()])(?=\1))(?=.*?[1-9])[0-9-()+ ]+$

The fourth bird
  • 154,723
  • 16
  • 55
  • 70