Jyoti Sahu
Jyoti Sahu

Reputation: 13

Regex pattern for Validating phone number

I have a input string ("My phone number is 860-678 - 2345"). From the input string I need to validate phone number using Regex.

I am using the below pattern but it doesn't work if the phone number contains white Space in it.

[(]?[2-9]{1}[0-9]{2}[)-. ,]?[2-9]{1}[0-9]{2}[-. ,]?[0-9]{4}

Thanks.

Upvotes: 1

Views: 8423

Answers (4)

TeJ
TeJ

Reputation: 450

This might help you:

(?\d{3})?-? *\d{3}-? *-?\d{4}

Refer: Regular Expression Liberary

Upvotes: 0

Adrian Wragg
Adrian Wragg

Reputation: 7401

The following regular expression:

(\([2-9]\d\d\)|[2-9]\d\d) ?[-.,]? ?[2-9]\d\d ?[-.,]? ?\d{4}

matches all of the following:

860-678-2345
(860) 678-2345
(860) 678 - 2345

and probably a fair amount else too. Broken down:

  • (\([2-9]\d\d\)|[2-9]\d\d) - Matches the first part of the number with or without brackets
  •  ?[-.,]? ? - A hyphen, period (or full stop to us Brits) or a comma, with or without surrounding spaces.
  • [2-9]\d\d - Matches the second part of the number.
  • \d{4} - Matches the final part of the number.

\d\d and [0-9]{2} are equivalent; the former is just slightly shorter so improves readability. Likewise, [2-9] and [2-9]{1} are equivalent; the {1} just means "one instance of the preceeding pattern", which is a given anyway.

Upvotes: 1

The best thing to do is to first take off all white spaces, and then, you can easily verify your numbers with that RE that you've done.

Upvotes: 0

Cemafor
Cemafor

Reputation: 1653

You could check for spaces seperately before and after the seperating charactors.

[(]?[2-9]{1}[0-9]{2}[ ]?[)-.,]?[ ]?[2-9]{1}[0-9]{2}[ ]?[-.,]?[ ]?[0-9]{4}

Keep in mind, this wont actually match the parens so something like (234-567, 1234 would match. So if you want more strict matching, you will need a much more complicated regex or code the validation using something else.

Upvotes: 0

Related Questions