phone icon indicating copy to clipboard operation
phone copied to clipboard

Support use in Rails validations

Open elskwid opened this issue 12 years ago • 2 comments

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

elskwid avatar Nov 17 '13 01:11 elskwid

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

milgner avatar Aug 26 '14 12:08 milgner

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

elskwid avatar Jan 31 '15 00:01 elskwid