Regex to allow only digits, hypens, space, parentheses and should end with a digit (javascript) [duplicate]

北慕城南 提交于 2019-12-05 12:46:47
staafl
^\(?\d{3}\)?[- ]?\d{3}[- ]?\d{4}$
Eugene

Well my idea is (after some searching) not new at all! Look at this:

A comprehensive regex for phone number validation

This is an Excellent suggestion btw.

This one is probably correct (assuming some parsing errors depending on the regex engine you are using. It's also ugly as hell :(.

(?:\d{3}(?:\d{7}|\-\d{3}\-\d{4}))|(?:\(\d{3}\)(?:\-\d{3}\-)|(?: \d{3} )\d{4})
(^\(?[0-9]{3}\)?\-?\s?[0-9]{3}\-?\s?[0-9]{4}[^-])

I tested this on http://regexhero.net/tester/ and got it to select the following patterns:

xxx-xxx-xxxx 
(xxx) xxx xxxx 
(xxx)-xxx-xxxx
xxxxxxxxxx

It ignored the following patterns:

xxx-xxx-xxxx- 
-xxx-xxx-xxxx

I hope this helps, or at least moves you in the correct direction.

This should do the trick:

/^([\d]{6}|((\([\d]{3}\)|[\d]{3})( [\d]{3} |-[\d]{3}-)))[\d]{4}$/
  • It starts by checking if the first 6 digits are xxxxxx,
  • if not it looks if the first three digits are (xxx) or just xxx
    • and if one of those it checks if the next three are xxx or -xxx-
  • At the end it checks that there are four trailing digits xxxx
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!