Skip to content

Instantly share code, notes, and snippets.

@chrisfinne
Last active January 4, 2016 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisfinne/8627754 to your computer and use it in GitHub Desktop.
Save chrisfinne/8627754 to your computer and use it in GitHub Desktop.
validate us canada phone number
class String
def is_us_phone?
!!(self.gsub(/\D/,'') =~/\A1?\d{10}\z/)
end
def to_us_phone
return nil unless is_us_phone?
s = self.gsub /\D/,''
s[0,1]=='1' ? s[0,11] : '1'+s[0,10]
end
@@bad_phones = 0.upto(9).collect{|t| '1'+t.to_s*10} + ['11231231234', '1231231234']
def is_bad_us_phone?
return true unless is_us_phone?
tmp_str = self.to_us_phone
# This is according to http://en.wikipedia.org/wiki/North_American_Numbering_Plan
return true unless tmp_str =~ /\A1[2-9][0-8]\d[2-9]\d{6}\z/
# These are some numbers that are common fakes, although some are valid, e.g. 333-333-3333
return true if @@bad_phones.include?(tmp_str)
# Ficticious numbers and directory assistance
return true if tmp_str =~ /55501\d{2}\z/ or tmp_str =~ /5551212\z/ or tmp_str =~/\A1555/
false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment