Skip to content

Instantly share code, notes, and snippets.

@JPaulDuncan
Last active March 2, 2023 21:37
Show Gist options
  • Save JPaulDuncan/7150144ba3bd166b359bb1095e781e10 to your computer and use it in GitHub Desktop.
Save JPaulDuncan/7150144ba3bd166b359bb1095e781e10 to your computer and use it in GitHub Desktop.
VIN Validation (Vehicle Identification Number)
function validateVin(vin) {
if (vin == "11111111111111111") { return false; }
if (!vin.match("^([0-9a-hj-npr-zA-HJ-NPR-Z]{10,17})+$")) { return false;}
var letters = [{ k: "A", v: 1 }, { k: "B", v: 2 }, { k: "C", v: 3 },
{ k: "D", v: 4 }, { k: "E", v: 5 }, { k: "F", v: 6 }, { k: "G", v: 7 },
{ k: "H", v: 8 }, { k: "J", v: 1 }, { k: "K", v: 2 }, { k: "L", v: 3 },
{ k: "M", v: 4 }, { k: "N", v: 5 }, { k: "P", v: 7 }, { k: "R", v: 9 },
{ k: "S", v: 2 }, { k: "T", v: 3 }, { k: "U", v: 4 }, { k: "V", v: 5 },
{ k: "W", v: 6 }, { k: "X", v: 7 }, { k: "Y", v: 8 }, { k: "Z", v: 9 }];
var weights = [8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2];
var exclude = ["I", "O", "Q"];
var val = 0;
for (var idx = 0; idx < vin.length; idx++) {
var item = vin.charAt(idx).toUpperCase();
if (exclude.contains(function (x) { return x == item; })) { return false; }
var pos = (item.match("^[0-9]+$") != null) ? parseInt(item) : letters.filter(function (letter) { return letter.k == item; })[0].v;
val += (pos * weights[idx]);
}
var checksum = (val % 11);
return (vin.charAt(8) == (checksum < 10 ? checksum.toString() : "X"));
};
@JPaulDuncan
Copy link
Author

doesn't work for Volkswagen cars

Europe doesn't require the 9th digit to be a check digit so it's pretty much useless to even try on European vehicle VINs.

Please feel free to modify accordingly!

@JDMathew
Copy link

Why 19 1's and not 17? if (vin == "11111111111111111") { return false; } surely this should be 17 1's?

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