phony_rails
phony_rails copied to clipboard
Validates extension and then after normalize it fails validation
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