joost / phony_rails

This Gem adds useful methods to your Rails app to validate, display and save phone numbers. It uses the super awesome Phony gem (https://github.com/floere/phony).
MIT License
556 stars 111 forks source link

Validates extension and then after normalize it fails validation #203

Open danielpclark opened 3 years ago

danielpclark commented 3 years ago

Given the number: 1 (432) 234-9838 #5426

The use of:

validates_plausible_phone :number
phony_normalize :number, country_code: 'US', normalize_when_valid: true

will validate the number before save, then normalize it into +14322349838 x5426, and then when attempting to save it it fails its own validation.

This is my custom Validator I wrote to get around this issue:

class PhonePlausibleValidator < ActiveModel::Validator
  def validate(record)
    number = record.number
    return unless number # presence: false

    extension_check = lambda { |number| number&.[]('x') && number.phony_normalized == number }

    record.errors.add(:number, "is an invalid number #{number}") \
      unless Phony.plausible?(number) ||
             Phony.plausible?(number, cc: 'US') ||
             extension_check.call(number)
  end
end

and I use it with:

validates_with PhonePlausibleValidator
phony_normalize :number, default_country_code: 'US', normalize_when_valid: true