Skip to content

Instantly share code, notes, and snippets.

@leods92
Last active December 22, 2015 02:48
Show Gist options
  • Save leods92/6405552 to your computer and use it in GitHub Desktop.
Save leods92/6405552 to your computer and use it in GitHub Desktop.
BrPhoneValidator. Validator para Rails (testado em 3.2) para validação de telefones brasileiros. Válido em 1º de setembro de 2013, em constante alteração já que celulares estão gradualmente adotando o 9º dígito.
class BrPhoneValidator < ActiveModel::EachValidator
# first 2 digits represent dialing code
# dialing codes in Brazil don't start with 0
#
# the following represent the phone
# must have 8 digits
# first digit must start with 2, 3, 4, 5 or 6
#
LANDLINE_REGEXP = /\A[1-9]\d[2-6]\d{7}\z/
# first 2 digits represent dialing code
# dialing codes in Brazil don't start with 0
#
# the following represent the phone
# must have 8 digits
# might have 9 if dialing code is 11, 12, 13, 14, 15, 16, 17, 18 or 19
# first digit must start with 7, 8 or 9
# might start with 5 as well if dialing code is 11
#
MOBILE_REGEXP = /\A(11(5|[7-9])\d{7,8}|1[2-9][7-9]\d{7,8}|[2-9]\d[7-9]\d{7})\z/
def validate_each(record, attr_name, value)
regexp = options[:mobile] ? MOBILE_REGEXP : LANDLINE_REGEXP
message = options[:mobile] ?
:invalid_br_mobile_phone :
:invalid_br_phone
unless value =~ regexp
record.errors.add attr_name, options[:message] || message
end
end
end
pt-BR:
errors:
messages:
invalid_br_phone: "não está no formato de telefone fixo"
invalid_br_mobile_phone: "não está no formato de telefone celular"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment