InesM
InesM

Reputation: 343

Validate phone number without country code

In my rails app my users can enter their phone number.

I'm using phonelib to validate phone numbers, however my service will only be available in one country so I don't want my users to enter the country code every time they enter their phone number to the server.

I tried to configure my phonelib.rb like so:

Phonelib.default_country = "CHE"

but still it gives me phone invalid if I don't enter the +41 country code when I try to enter a phone number.

Is it possible to do it throw phonelib or is other solutions better?

Upvotes: 0

Views: 2670

Answers (2)

Khalil Gharbaoui
Khalil Gharbaoui

Reputation: 7042

You could just capture any phone number regardless but have a custom validator for that uses Phonelib.

This here validates the input and tells the user what it expects.

app/models/model_name.rb

validates_with PhoneCountryCodeValidator, fields: [:client_mobile], country_codes: ["CH", :ch, Phonelib.default_country]

app/models/concerns/phone_country_code_validator.rb

class PhoneCountryCodeValidator < ActiveModel::Validator
  def validate(record)
    options[:fields].any? do |field|
      phone_number = record.send(field)
      phone_country = Phonelib.parse(phone_number).country
      phone_country_code = phone_country.to_s.upcase

      options[:country_codes].any? do |valid_country|
        valid_country_code = valid_country.to_s.upcase
        unless phone_country_code == valid_country_code
          record.errors.add(field, "has an invalid country code:
            #{phone_country_code} should be #{valid_country_code}")
        end
      end
    end
  end
end

Also checkout this issue for more details: https://github.com/daddyz/phonelib/issues/136

Upvotes: 1

Alberto
Alberto

Reputation: 878

From a "future proof" standpoint I would still advise on keeping the country codes there.

You could have the country code showing up by default on all phone fields so users don't have to type it if there's only one country code, but that way you'd be making sure your data quality.

Anyway, just my 2 cents..

Upvotes: 1

Related Questions