Class: PhoneNumberFormatValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
app/validators/phone_number_format_validator.rb

Overview

Validate fields to look like phone numbers

Is not an exhaustive check, works by stripping all non-digits out and looking for a string with at least 10 digits.

A blank phone number is considered valid (use presence validator to check for that)

Examples

validates :phone_number, phone_number_format: true                 # optional
validates :phone_number, phone_number_format: true, presence: true # required

Constant Summary collapse

PHONE_NUMBER_REGEX =
/\A[ \d\+\-\(\)ext\.\/]{10,}\z/i

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attr_name, value) ⇒ Object



16
17
18
19
# File 'app/validators/phone_number_format_validator.rb', line 16

def validate_each(record, attr_name, value)
  return if value.blank?
  record.errors.add(attr_name, :phone_number_format, options) unless value =~ PHONE_NUMBER_REGEX
end