class ActiveModel::Validations::CpfValidator

Public Instance Methods

validate_each(record, attribute, value) click to toggle source
# File lib/validates_cpf.rb, line 9
def validate_each(record, attribute, value)
  return if (options[:allow_nil] and value.nil?) or (options[:allow_blank] and value.blank?)
  return if (options[:if] == false) or (options[:unless] == true)
  return if (options[:on].to_s == 'create' and not record.new_record?) or (options[:on].to_s == 'update' and record.new_record?)

  if value.to_s.gsub(/[^0-9]/, '').length <= 11
    if (not value.to_s.match(/\A\d{11}\z/) and not value.to_s.match(/\A\d{3}\.\d{3}\.\d{3}\-\d{2}\z/)) or not Cpf.valid?(value)
      record.errors.add(attribute, 'The CPF is invalid')
    end
  end
end