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

我的未来我决定 提交于 2019-12-22 09:00:07

问题


Possible Duplicate:
US Phone Number Verification

I need to validate US phone number. It could be in the format:

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

but it should not be

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

It should accept digits, hyphens, space and parentheses.

Currently I use

^\[0-9 \-\. ]+$ 

which does not validate dash at the beginning or end.


回答1:


^\(?\d{3}\)?[- ]?\d{3}[- ]?\d{4}$



回答2:


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.




回答3:


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})



回答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.




回答5:


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


来源:https://stackoverflow.com/questions/12101125/regex-to-allow-only-digits-hypens-space-parentheses-and-should-end-with-a-dig

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!