Validating Phone Number in Ruby

Validating phone number in ruby

There are many gems that will do this for you.

Take a look at: http://rubygems.org/search?utf8=%E2%9C%93&query=phone+number

This one looks like it will do what you need -- it essentially implements a regex to validate the phone number: http://rubygems.org/gems/validates_phone_number

For US, Canada (Bermuda, Bahamas... etc and all +1 numbers) there are other rules that the regex should follow. The first digit (after the +1) must be 2-9.

For a full list see: http://en.wikipedia.org/wiki/North_American_Numbering_Plan

basic phone number validating regex

Your Regex matches the following:

  • \d, that is a number character
  • followed by 11, 12 or 13 characters from the range of 0-9
  • followed by the end of the string

As such, your regular expression currently matches a numeric string with between 12 and 14 numeric chars at the end. It does not match a numeric string containing only 11 characters. Anything at the start of the string before that is ignored (i.e. your regex would also match foobar 1234567891012)

To fix your regex, you could simplify it to

/\A\d{10,13}\z/

This regex would match the following:

  • the start of the string
  • followed by 10 to 13 numeric characters
  • followed by the end of the string

Pure ruby UK phone number validator

If you want to avoid gems and regexes, you're doing Rails in hard mode. I would strongly suggest you devote some time to getting comfortable with both.

Parsing phone numbers is always more complicated than you think. For example, your assumption that "UK phone numbers are 11 digits long when in the 07... format and always have 7 after the prefix (whether it's +44, 44 or 0)" is not correct. 07 is just a really common prefix.

It's best to leave it as someone else's problem, so if there's a gem use it. For example, uk-phone-number-formatter seems to do exactly what you want and it is tiny.


Let's say we do this without regexes and without gems and assume 07 is the only prefix. First, separate the problem into two steps.

  1. Normalization
  2. Validation

Normalization is reformatting the phone number so that equivalent phone numbers look the same. Validation is validating its a phone number. Validation is much easier if the data has already been normalized.

That means stripping everything that isn't a digit, fixing the prefx, and adding the + at the front.

Stripping everything that isn't a digit is easy with gsub: phone.gsub!(/\D+/). Or the non-regex delete: phone.delete('^0-9').

Now with non-numbers out of the way, we just want to change "07" into "447".

Finally, add the +.

def normalize(phone)
# Strip non-digits.
normalized = phone.delete('^0-9')

# Replace 07x with 447x
if normalized[0..1] == "07"
normalized[0] = "44"
end

# Add the plus.
return "+#{normalized}"
end

Now that it's normalized, validation is easy.

# We assume the phone number is validated.
def phone_is_uk_format(phone)
errors.add(:phone, :missing_prefx, message: "Missing +447 prefix")
if normalized[0..3] != "+447"

# 12 because of the leading +
errors.add(:phone, :wrong_length, message: "A phone number is 11 digits")
if normalized.length != 12
end

And integrating it with a model...

class Person < ApplicationRecord
validate :phone_is_uk_format

# Normalize the phone number when it is set.
def phone=(number)
super(normalize_uk_phone(number))
end

private def phone_is_uk_format
# Validating presence is different.
return if phone.blank?

errors.add(:phone, :missing_prefx, message: "Missing +447 prefix")
if phone[0..3] != "+447"

# 12 because of the leading +
errors.add(:phone, :wrong_length, message: "A phone number is 11 digits")
if phone.length != 12
end

private def normalize_uk_phone(phone)
# Strip non-digits.
normalized = phone.delete('^0-9')

# Replace 07x with 447x
if normalized[0..1] == "07"
normalized[0] = "44"
end

# Add the plus.
return "+#{normalized}"
end
end

Validating the phone number with a regex ruby

I use this, :with => "no problem".

validates :phone,:presence => true,
:numericality => true,
:length => { :minimum => 10, :maximum => 15 }

If you want a message,(not a MASSAGE), try this,

 validates :phone,   :presence => {:message => 'hello world, bad operation!'},
:numericality => true,
:length => { :minimum => 10, :maximum => 15 }

Also check this question.

Phone Number Regex in Ruby -- Anchor error with ^$

The issue is at this line

VALID_PHONE_NUMBER_REGEX = /^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/

it should be changed to

VALID_PHONE_NUMBER_REGEX = /\A(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}\z/

Personally, I would suggest to avoid trying to use a single regex to validate all those formats. Either group similar formats, and use different regexps, or normalize the input and validate a few formats.

You may also want to have a look at Phony.

Ruby validation of name, email, and phone number

I suspect you didn't intend to use the assignment operator here:

if (email = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i)

Try this:

if email =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i

You have a similar error in the phone_number method:

if number = 10

I'm not sure what you intended here. Perhaps this?

if number.size == 10

You have more problems, however. Take a look at this loop:

loop do
if number.size == 10
break
else
puts "Invalid phone number entered. Please try again."
end
end

How will the user ever exit this loop if the number is invalid? The value of number never changes.

phone number validation regex in rails

\A(?:\+?\d{1,3}\s*-?)?\(?(?:\d{3})?\)?[- ]?\d{3}[- ]?\d{4}\z

You can another optional group .See demo.

https://regex101.com/r/fM9lY3/20

REGEX for phone number - Ruby

Working example https://regex101.com/r/oZ2yQ0/1

\(\d{7}\)

\( matches the character ( literally
\d{7} match a digit [0-9]
Quantifier: {7} Exactly 7 times
\) matches the character ) literally

Validate phone-number format in Rails 4 - REGEX

Change /\A(\d{10}|\(?\d{3}\)?[-. ]\d{3}[-.]\d{4})\z/ to:

/\A(\(?(809|829|849)\)?[-. ]\d{3}[-.]\d{4})\z/

I took the liberty of dropping the part where you are matching any ten digit number - not sure why it was there or how it should be used in your context.



Related Topics



Leave a reply



Submit