Skip to content

Instantly share code, notes, and snippets.

@danielnass
Created February 5, 2015 21:46
Show Gist options
  • Save danielnass/d41d47a9b6e05918a56c to your computer and use it in GitHub Desktop.
Save danielnass/d41d47a9b6e05918a56c to your computer and use it in GitHub Desktop.
jQuery Validation Additional Method CNH - Carteira Nacional de Habilitação - Carteira de Motorista
$.validator.addMethod('CNH', function(value, element) {
var ret,
cnh = value,
firstChar = cnh.charAt(0);
if (cnh.replace(/[^\d]/g, '').length === 11 && firstChar.repeat(11) !== cnh) {
var dsc = 0;
for (var i = 0, j = 9, v = 0; i < 9; ++i, --j) {
v += +(cnh.charAt(i) * j);
}
var 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,
vl2 = (x >= 10) ? 0 : x - dsc;
ret = '' + vl1 + vl2 === cnh.substr(-2);
}
if (ret !== true) return false;
return true;
}, 'CNH inválida');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment