Fulvio
Fulvio

Reputation: 965

Validate phone-number format in Rails 4 - REGEX

I'm working on a small project where the user should type the phone numbers, so I would like to validate that information using the "ClientSideValidations" gem.

validates_format_of :telcasa, :celular, :tel_flia, :tel_trab, :tel_ref_2, :tel_ref_1, 
    length: { in: 10 },
    :with => /\A(\d{10}|\(?\d{3}\)?[-. ]\d{3}[-.]\d{4})\z/,
    :message => "Formato invalido"

But, for the region where this project is going to be used I have to validate the three first numbers of the phone that correspond to the area code ("809"/"829"/"849"). How can I validate that the user correctly typed the phone number with one of the three area codes?

Upvotes: 2

Views: 4111

Answers (2)

Cyril Duchon-Doris
Cyril Duchon-Doris

Reputation: 13949

You can write some custom validation

validate do
  valid_phone_codes = [ "007", "042", ...]
  valid_phone_codes.each do |valid_code|
    # Also handle optional parenthesis
    return true if self.phone_number.starts_with?(valid_code, "(#{valid_code})")
  end
  errors.add(:phone_numbers, "Must start with a valid country code (one of #{valid_phone_codes.join(', ')}")
  false
end

Or if you prefer, you can declare this code in a function def valid_country_codes, and then add a line

validate :valid_country_codes

Upvotes: 0

steve klein
steve klein

Reputation: 2629

Change /\A(\d{10}|\(?\d{3}\)?[-. ]\d{3}[-.]\d{4})\z/ to:

/\A(\(?(809|829|849)\)?[-. ]\d{3}[-.]\d{4})\z/

I took the liberty of dropping the part where you are matching any ten digit number - not sure why it was there or how it should be used in your context.

Upvotes: 1

Related Questions