Regular expression for validating phone
I need to validate textbox for validating phone number in C# allowing only hyphens(-) and integer val开发者_如何学编程ues.
I want a regular expression which allows only those.
Thanks in advance
Try the following one:
"^[0-9]+(-[0-9]+)*$"
It allows for numbers interspersed with hyphens, but not double hyphens, so "3-4" is correct, but "23--5" isn't.
Assuming you validate in C#:
var regex = new Regex(@"^(?:[0-9]+(?:-[0-9])?)*$");
However, I would also accept country codes (you need plus prefix) and spaces. The spaces should be accepted because user may enter them and they are easy to strip from the string when it is stored into database. When the string is shown to the user it should be reformatted to have some spaces.
EDIT: I liked markijbema's version that does not accept double hyphens so I changed this to have similar matching.
C#.net have it's own expression editor
here is an example "(((\d{3}) ?)|(\d{3}-))?\d{3}-\d{4}"
精彩评论