faqts : Computers : Programming : Languages : JavaScript : Forms : TextAreas/TextFields

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

10 of 11 people (91%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

How can I validate for having ONLY 3 letters at the begining, then 6 numbers after (always this form

Mar 11th, 2002 08:42
Jean-Bernard Valentaten, sanjuT sanjuT,


This is quite easy, since js features a function called isNaN, which 
will return true is the given value is Not A Number.
function isCorrectPattern(myValue)
{
  var retBool = true;
  for (i = 0; i < 9; i++)
  {
    if (i < 3)
    {
      retBool = retBool && isNaN(parseInt(myValue.charAt(i)));
    }
    else
    {
      retBool = retBool && !(isNaN(parseInt(myValue.charAt(i))));
    }
  }
  return retBool;
}
This will check the value for your pattern. The first three steps of 
the for-loop will check for characters that are not numbers (letters 
and other chars), the last six loops will check for integers (numbers).
The trick is, that parseInt will return NaN if the first character of a 
string to be parsed is not integer (0 - 9), this is passed to isNaN, 
which will return a boolean value (true or false). This boolean can 
then be multiplied (and-operation) with the boolean we already have.
We have to use an and-operation, since this will "store" any false 
input (true && false = false).
This behaviour is the proovf of correctness for the algorithm, and the 
reason, why we have to initialize the return value as beeing 'true' 
(otherwise it would always return 'false').
If you wish to check whether your value is exactly nine characters 
long, you'll need to enclose the for-loop in an if statement:
...
if (myValue.length == 9)
{
  for...
}
else
  retBool = false;
...
this will make sure, that the cpu won't process unnessesary information 
(code efficiency!!).
HTH,
Jean