Search code examples
regexvalidation

VIN Validation RegEx


I have written a VIN validation RegEx based on the http://en.wikipedia.org/wiki/Vehicle_identification_number but then when I try to run some tests it is not accepting some valid VIN Numbers.

My RegEx:

^[A-HJ-NPR-Za-hj-npr-z\\d]{8}[\\dX][A-HJ-NPR-Za-hj-npr-z\\d]{2}\\d{6}$

VIN Number Not Working:
1ftfw1et4bfc45903
WP0ZZZ99ZTS392124

VIN Numbers Working:
19uya31581l000000
1hwa31aa5ae006086

(I think the problem occurs with the numbers at the end, Wikipedia made it sound like it would end with only 6 numbers and the one that is not working but is a valid number only ends with 5)

Any Help Correcting this issue would be greatly appreciated!


Solution

  • I can't help you with a perfect regex for VIN numbers -- but I can explain why this one is failing in your example of 1ftfw1et4bfc45903:

    ^[A-HJ-NPR-Za-hj-npr-z\d]{8}[\dX][A-HJ-NPR-Za-hj-npr-z\d]{2}\d{6}$
    

    Explanation:

    • ^[A-HJ-NPR-Za-hj-npr-z\d]{8}
      This allows for 8 characters, composed of any digits and any letters except I, O, and Q; it properly finds the first 8 characters:
      1ftfw1et
    • [\dX]
      This allows for 1 character, either a digit or a capital X; it properly finds the next character:
      4
    • [A-HJ-NPR-Za-hj-npr-z\d]{2}
      This allows for 2 characters, composed of any digits and any letters except I, O, and Q; it properly finds the next 2 characters:
      bf
    • \d{6}$
      This allows for exactly 6 digits, and is the reason the regex fails; because the final 6 characters are not all digits:
      c45903