class PhoneNumberValidator::Validator

This class does all of the matching and checking work for the validation of the phone number.

Constants

PHONE_NUMBER_REGEX

The regex pattern for validating US phone numbers

Regular Expression tested using regexr.com

The regular expression used can be found in README.rdoc on the documentation's home page

Public Class Methods

new(phone_number = '+1 (987) 654-3210 ext. 198842') click to toggle source

Initializes the @phone_number instance variable

# File lib/phone_number_validator/validator.rb, line 15
    def initialize(phone_number = '+1 (987) 654-3210 ext. 198842')
@phone_number = phone_number
    end

Public Instance Methods

validate() click to toggle source

Checks to see if the phone number the user entered is valid by testing regex the pattern with the phone number

Return Type: boolean or nil

Examples

Ex. 1

require 'phone_number_validator'

check_phone_number = PhoneNumberValidator.validate_phone_number('+1 (987) 654-3210 ext. 198842')

print check_phone_number
Output
true

Ex. 2

require 'phone_number_validator'

check_phone_number = PhoneNumberValidator.validate_phone_number('+1 (987 778873-321a0 ext.ff99')

print check_phone_number
Output
false

Ex. 3

require 'phone_number_validator'

check_phone_number = PhoneNumberValidator.validate_phone_number('')

print check_phone_number
Output
nil
# File lib/phone_number_validator/validator.rb, line 61
def validate
  if (@phone_number.match(PHONE_NUMBER_REGEX))
    return true
  elsif (@phone_number == '' || @phone_number == nil)
    return nil
  else
    return false
  end
end