Trying to validate a form that contains information about a car. Have all the validation completed apart from part for the registration number, the format it has to be entered is two letters, a hyphen, last two digits of the year its from, another hyphen, then 3 letters. eg GT-00-TRE. I have the validation for the last three letters, however not sure on how to check theat there are only two letters before the first hyphen and that after the first hyphen there are two numbers. The code i have for this part is:

// get length of reg number entered
        var len = theForm.registrationNumber.value.length; 

        // get position of last occurance of '-'
        var lastDotPos = theForm.registrationNumber.value.lastIndexOf('-'); 

        // get number of chars after last '.'
        var numCharsAfterLastDot=len-lastDotPos; 

        // need to decrement numCharsAfterLastDot as lastIndexOf counts from 0

        // check if a . character appears less than 2 or more than 3 characters from the end of the email       
        if (numCharsAfterLastDot<3)  
            errorStr = errorStr + "\nInvalid registration number - less than 3 characters following last -";

        if (numCharsAfterLastDot>4)  
            errorStr = errorStr + "\nInvalid reg  number - more than 4 characters following last -";

two letters, a hyphen, last two digits of the year its from, another hyphen, then 3 letters

What other criteria or restriction of those set of letters/numbers? The simpliest way to check string is to use regular expression. It may be a bit over your head for now, but you may search on the Internet and read what regular expression is. Anyway, the validate the part which you are trying to do could be done in 1 line of code.

// This regular expression attempts to match a string started with
// 2 capitalized letters followed by a hyphen followed by
// 2-digit number followed by a hyphen followed by
// 3 capitalized letters.
// If you want it to be case in-sensitive, add "i" at the end of //
//   i.e. match(/^[A-Z]{2}\-\d{2}\-[A-Z]{3}$/i)
if (!theForm.registrationNumber.value.match(/^[A-Z]{2}\-\d{2}\-[A-Z]{3}$/)) {
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.