Created
December 23, 2022 03:24
-
-
Save HDias/1dc8478240de6359c52537c94ffa3d2a to your computer and use it in GitHub Desktop.
CNS validator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def valid_cns?(cns) | |
# Verifica se o tamanho do CNS está correto | |
return false unless cns.length == 15 | |
# Verifica se os primeiros 14 dígitos são números | |
return false unless cns[0..13].scan(/\D/).empty? | |
# Verifica se o último dígito é um número ou uma letra | |
return false unless cns[14] =~ /[\dX]/ | |
# Verifica se o dígito verificador é válido | |
check_digit = cns[14] | |
if check_digit == 'X' | |
check_digit = 10 | |
else | |
check_digit = check_digit.to_i | |
end | |
weight = [7, 4, 3, 2, 1, 7, 4, 3, 2, 1, 7, 4, 3, 2] | |
sum = 0 | |
(0..13).each do |i| | |
sum += cns[i].to_i * weight[i] | |
end | |
mod = sum % 11 | |
mod = 11 - mod unless mod == 0 | |
mod == check_digit | |
end | |
# Exemplo de uso | |
puts valid_cns?("111111111111111") # false, número inválido | |
puts valid_cns?("111111111111112") # true, número válido |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment