Search code examples
ruby-on-railsregexruby-on-rails-4

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


Solution

  • \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