Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validates extension and then after normalize it fails validation #203

Open
danielpclark opened this issue Jan 7, 2021 · 0 comments
Open

Comments

@danielpclark
Copy link

danielpclark commented Jan 7, 2021

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant