-1

I want to validate the phone number Like 1-12 -123 using regex and I have tried like

/^[0-9 -]+$/

and

/^[0-9,\- ]+$/

Iam using it like

/^[0-9 -]+$/.test(value)

And it is accepting 0-9 numbers and - also but not accepting the spaces.I have tried in many ways but did'nt got any solution.Can anyone suggest me.Thanks in Advance

Simon Forsberg
  • 13,086
  • 10
  • 64
  • 108
GautamD31
  • 28,552
  • 10
  • 64
  • 85

5 Answers5

0

you can use [ -0-9]+ (leave a space after the first square bracket) to allow spaces, dashes and numbers

Savv
  • 433
  • 2
  • 7
  • 1
    @Gautam3164 Show the code you are using together with the regex. (Edit your question and provide this, do not post that code in a comment) – Simon Forsberg Oct 21 '13 at 13:09
  • @SimonAndréForsberg see my edit once...BTW I didnt gave any code in my comment – GautamD31 Oct 21 '13 at 13:11
  • @Gautam3164 sorry, didn't see how much reputation you had :) I guess you're quite used to StackOverflow then so you know better than to post a lot of code in a comment :P – Simon Forsberg Oct 21 '13 at 13:15
0

What I'd recommend is trimming out the spaces and the - from the field, and then validate the digits only. Because I doubt

-----0-4  023 - 331 34    124
00000                      -
-

etc

should be considered a valid phone-numbers?

And if you then try to make a phone-number regex to take that into considerations you'll either not succeed, or run into an expression that's so complex that it's not maintainable.

So instead trim your input/format your input into a format you control, which you then easily can validate and use that.

If you really want to go a Regular Expression route, I'd think something like

^[1-9]([ \-0-9][0-9]+)+$ 

is what you're after. (if the number must not start with 0, otherwise replace the first [1-9] with [0-9]) Also change the final + into {0;y} for how many blocks of numbers you allow etc if there's a limit/focus on how many 'blocks' of numbers you allow. Regular expressions can quickly become very complex.

Allan S. Hansen
  • 4,013
  • 23
  • 25
0

For javascript :

var phoneNumber = "1-12 -123";
var test = /^[0-9 -]+$/.test(phoneNumber);

alert(test); // Here, return true

If you code in PHP, this code will match your phone number.

<?php

$phoneNumber = '1-12 -123';

if(preg_match('/^[0-9 -]+$/', $phoneNumber)) {
    echo "Phone number is valid";
}

Edit: Ok, use the right tag next time.

Fabien Sa
  • 9,135
  • 4
  • 37
  • 44
0

this one works [0-9 -]+, this doesn't work [0-9- ]+ (order matters)

Yann Moisan
  • 8,161
  • 8
  • 47
  • 91
-2

For spaces you need to put a \s in your alphabet.

/^[0-9\s-]+$/
Jonathon
  • 15,873
  • 11
  • 73
  • 92