user3574603
user3574603

Reputation: 3618

Rails/Phonelib: Why does my telephone number validator fail?

I am using PhoneLib (https://github.com/daddyz/phonelib) to validate my phone numbers.

I have a model Subscription with a column phone_number.

I'm testing this phone number: 3052612151.

I can see that Phonelib considers it to be a valid number:

> Phonelib.valid_for_country? "3052612151", :us
#=> true

However, when I use Phonelib's validator, my record is not considered to be valid.

class Subscription < ApplicationRecord
  validates :email, presence: true
  validates :phone_number, phone: { countries: :us }
> s = Subscription.create(phone_number: '3052612151', email: '[email protected]')
> s.valid?
#=> false
> s.errors.full_messages
#=> ["Phone number is invalid"]

I've been scratching my head for over an hour. Can anyone see what I've done wrong? Why does Phonelib consider the number to be valid when calling #valid_for_country? but not when used as a validator?

Upvotes: 2

Views: 1526

Answers (2)

arieljuod
arieljuod

Reputation: 15838

Try using countries: [:us], the validator actually does a & operation and checks if the size is greater than 0, maybe it's expecting an array. https://github.com/daddyz/phonelib/blob/master/lib/validators/phone_validator.rb#L85

The validator actually checks 4 validations, it's a really bad design that all validations return the same error message, weird :S. https://github.com/daddyz/phonelib/blob/master/lib/validators/phone_validator.rb#L63

Upvotes: 1

Mark Merritt
Mark Merritt

Reputation: 2695

The only thing I can think of is maybe you should set the default country in an initializer

# config/initializers/phonelib.rb
Phonelib.default_country = "US"

Then just use validates :phone_number, phone: true in your model.

Upvotes: 1

Related Questions