Class: ActiveModel::Validations::BrCnpjValidator
- Inherits:
-
EachValidator
- Object
- EachValidator
- ActiveModel::Validations::BrCnpjValidator
- Defined in:
- lib/custom_validations/br_cnpj_validator.rb
Constant Summary collapse
- BLACK_LIST =
%w(00000000000000 11111111111111 22222222222222 33333333333333 44444444444444 55555555555555 66666666666666 77777777777777 88888888888888 99999999999999)
Instance Method Summary collapse
Instance Method Details
#valid_cnpj?(cnpj) ⇒ Boolean
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/custom_validations/br_cnpj_validator.rb', line 15 def valid_cnpj? cnpj begin cnpj = (cnpj.is_a?(String) ? cnpj : cnpj.to_s) rescue Exception => exc return false end # could be 13 or 14 digits or with mask 99.999.999/9999-99 if cnpj !~ /^\d{13,14}$|\d{2}\.\d{3}\.\d{3}\/\d{4}\-\d{2}$/ return false end cnpj = cnpj.scan(/\d/).collect(&:to_i) cnpj.unshift(0) if cnpj.length == 13 # filter black list if BLACK_LIST.include? cnpj.join return false end # calculate first digit factor = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] sum = (0..11).inject(0) do |sum, i| sum + cnpj[i] * factor[i] end result = sum % 11 result = result < 2 ? 0 : 11 - result if result != cnpj[12] return false end # calculate second digit factor.unshift 6 sum = (0..12).inject(0) do |sum, i| sum + cnpj[i] * factor[i] end result = sum % 11 result = result < 2 ? 0 : 11 - result result == cnpj[13] end |
#validate_each(record, attribute, value) ⇒ Object
10 11 12 13 |
# File 'lib/custom_validations/br_cnpj_validator.rb', line 10 def validate_each(record, attribute, value) return if value.to_s.blank? # it doesn't validate presence record.errors.add(attribute, :br_cnpj, ) unless valid_cnpj?(value.to_s) end |