简体   繁体   中英

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.

eg

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.

This regex should work:

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

Working Demo

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-()]*/

正则表达式可视化

Debuggex Demo

这个:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM