Shikhar Subedi
Shikhar Subedi

Reputation: 616

javascript regex to allow numbers and special characters but not zeroes only

I need a javascript regex for validation of numbers that are phone numbers. The numbers cannot be a single zero or only zeroes.

e.g

0
000
00000-000-(000)

these are not allowed.

But these are allowed:

01-0808-000
10(123)(1234)
11111

The javascript regex I have so far is:

  /^[!0]*[0-9-\)\(]+$/

But this does not seem to work.

The rule is the phone number can contain numbers and - and ( and ). It can start with a 0 but the phone number cannot be a single 0 or a number of zeroes only with or without the above characters.

Could you point me in the right direction. Thanks in advance.

Upvotes: 6

Views: 37117

Answers (4)

Raul Guiu
Raul Guiu

Reputation: 2404

This one:

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

Upvotes: 0

anubhava
anubhava

Reputation: 785008

This regex should work:

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

Working Demo

Upvotes: 7

Mosho
Mosho

Reputation: 7078

Can try this:

/[0-9-()]*[1-9][0-9-()]*/

Will match any number of allowed chars and digits, but if there is no 1-9 anywhere the middle part won't get matched.

/[0-9-()]*[1-9][0-9-()]*/

Regular expression visualization

Debuggex Demo

Upvotes: 2

aelor
aelor

Reputation: 11116

IMO you should do something like this :

var str = "10(123)(1234)";
var res = str.replace(/[^\d]/g, '');
var fres = /^0+$/.test(res);
if(fres)
  console.log("Not a valid phone number");
else
  console.log("valid phone number");

this will tell you whether your phone number is valid or not based on the content of zeroes. If all zeroes and no other digit is present, then it will return true else false

Upvotes: 0

Related Questions