carr / phone

Ruby library for phone number parsing, validation and formatting
Other
395 stars 139 forks source link

Support use in Rails validations #47

Open elskwid opened 10 years ago

elskwid commented 10 years ago

17 was asking how to use phone in model validations. This would be a nice feature but it isn't on the roadmap.

milgner commented 10 years ago

Actually this is quite simple, posting just in case someone is looking for it:

class PhoneNumberValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    return if value.nil? || value.empty? || Phoner::Phone.valid?(value)
    record.errors.add(attribute, I18n.t('errors.messages.invalid'))
  end
end

And then in your model:

class User < ActiveRecord::Base
  validates :phone_number, phone_number: true
end
elskwid commented 9 years ago

@milgner do you mind if I add something like this to the README? (Or you could too. :smile:)