0

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
        numCharsAfterLastDot--;

        // 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 -";
            isCorrect=false;
        }

        if (numCharsAfterLastDot>4)  
        {
            errorStr = errorStr + "\nInvalid reg  number - more than 4 characters following last -";
            isCorrect=false;
        }
2
Contributors
1
Reply
3
Views
5 Years
Discussion Span
Last Post by Taywin
0

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}$/)) {
  alert("Invalid!")
  return
}

Edited by Taywin

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.