简体   繁体   中英

Regular expression for validating phone

I need to validate textbox for validating phone number in C# allowing only hyphens(-) and integer values.

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

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