Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

phone number validation regex in rails

Hi I need to validate phone number in these formats +1-541-754-3010 , (123) 986-5470 and 123-569-8740 I have given following regex

validates :phone, format: { with: /\A\(?\d{3}\)?[- ]?\d{3}[- ]?\d{4}\z/,
                              message: I18n.t('global.errors.phone_format')}

It working for (123) 986-5470 and 123-569-8740 but not for

+1-541-754-3010
754-3010 Local
(541) 754-3010 Domestic
+1-541-754-3010 International
1-541-754-3010 Dialed in the US
001-541-754-3010 Dialed from Germany
191 541 754 3010 Dialed from France

Please guide me how to solve this.Thanks in advance

like image 616
Dinshaw Raje Avatar asked Aug 04 '15 12:08

Dinshaw Raje


2 Answers

\A(?:\+?\d{1,3}\s*-?)?\(?(?:\d{3})?\)?[- ]?\d{3}[- ]?\d{4}\z

You can another optional group .See demo.

https://regex101.com/r/fM9lY3/20

like image 50
vks Avatar answered Sep 28 '22 09:09

vks


More advanced case, for example with Ukrainian local phone numbers like 050 555 33 22

^(?:\+?\d{1,3}[- ]?)?\(?(?:\d{3})?\)?[- ]?\d{3}[- ]?\d{2}[- ]?\d{2}$

https://regex101.com/r/YexwM5/3

like image 31
greenif Avatar answered Sep 28 '22 08:09

greenif