Skip to content

Instantly share code, notes, and snippets.

@felipecwb
Last active November 16, 2022 01:16
Show Gist options
  • Save felipecwb/f32f70bf05bdf1ec5663 to your computer and use it in GitHub Desktop.
Save felipecwb/f32f70bf05bdf1ec5663 to your computer and use it in GitHub Desktop.
CNH (Carteira Nacional de Habilitação) validation in JS
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);
}
@felipecwb
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment