Class: ActiveModel::Validations::CpfValidator

Inherits:
EachValidator
  • Object
show all
Includes:
ValidatesCpf
Defined in:
lib/validates_cpf.rb

Constant Summary

Constants included from ValidatesCpf

ValidatesCpf::VERSION

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
# 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