简体   繁体   中英

Matching phone number with letters - regex

How can I create a regular expression in javascript for phone numbers with this format? I need to validate that the phone number is as follows

1800YOUSAVE OR 800YOUSAVE OR 8001234567 OR 18001234567

All the above should be ok. I have the following based on another post i saw here on stack overflow but it fails on 1800YOUSAVE or 800YOUSAVE. For all these at least the first 3 should be numbers.

var reg1 = /^(?:(?:[0-9]{3}[a-zA-Z0-9]{4,})|(?:[0-9]{1,}))$/; //less than 10
var reg2 = /^(?:(?:[2-9]{3}[a-zA-Z0-9]{7})|(?:[2-9]{1}[0-9]{2,}))$/; //10 digits
var reg3 = /^(?:(?:[1-9]{1}[0-9]{3}[a-zA-Z0-9]{10})|(?:[1-9]{11}))$/; //11 digits
var reg4 = /^(?:(?:[0-9]{7}[a-zA-Z0-9]{7})|(?:[0-9]{1,15}))$/; //12 or more

Seems to me you want an optional leading "1" followed by "800" followed by either 7 letters or 7 digits, so the following should suit:

  var re = /^1?800[a-z]{7}$|^1?800[0-9]{7}$/i;

  alert(re.test('800yousave'));    // true
  alert(re.test('1800yousave'));   // true
  alert(re.test('1800yousavee'));  // false

  alert(re.test('8001234567'));    // true
  alert(re.test('18001234567'));   // true
  alert(re.test('180012345678'));  // false

There are benefits to keeping it simple. You can also do:

  var re = /^1?800(?:[a-z]{7}|[0-9]{7})$/i;

Edit

If you want three digits rather than "800", you can use:

  var re = /^1?\d{3}(?:[a-z]{7}|[\d]{7})$/i;

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