Last active
November 16, 2022 01:16
-
-
Save felipecwb/f32f70bf05bdf1ec5663 to your computer and use it in GitHub Desktop.
CNH (Carteira Nacional de Habilitação) validation in JS
This file contains 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
function validateCNH(cnh) { | |
var char1 = cnh.charAt(0); | |
if (cnh.replace(/[^\d]/g, '').length !== 11 || char1.repeat(11) === cnh) { | |
return false; | |
} | |
for (var i = 0, j = 9, v = 0; i < 9; ++i, --j) { | |
v += +(cnh.charAt(i) * j); | |
} | |
var dsc = 0, | |
vl1 = v % 11; | |
if (vl1 >= 10) { | |
vl1 = 0; | |
dsc = 2; | |
} | |
for (i = 0, j = 1, v = 0; i < 9; ++i, ++j) { | |
v += +(cnh.charAt(i) * j); | |
} | |
var x = v % 11; | |
var vl2 = (x >= 10) ? 0 : x - dsc; | |
return ('' + vl1 + vl2) === cnh.substr(-2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
jquery plugin validation: https://gist.github.com/danielnass/d41d47a9b6e05918a56c
tks @danielnass