"VERIFYING NUMBERS" > Page 1, 2, 3,
4, 5
Credit Card Numbers and ZIP Codes
When verifying credit card numbers, ZIP codes and the like, usually the only
things you care about are:
- That the user enters the correct number of digits
- That the user enters only numbers, and no other characters
In a ZIP code, for example, you would want the user to enter five characters
all of which are numbers. An example would be "90210."
Checking the length of the string is easy.
if (myString.length != 5) {return false;}
Verifying that each digit is actually a number takes a little more work, but
here's the way I do it.
First, we'll set up a for loop to cycle through each of the characters.
Then, we'll check each character against each number (0-9) to see if it
matches. If we find a match every time, we're okay. Here's what I'm
saying in code:
// Cycle through each number
for (var i = 0; i < myString.length; i++)
{
// We haven't found a match yet...
isNumber = 0;
// Cycle through 0-9, and set isNumber if we find one
for (var j=0; j<10; j++) if ("" + j == myText.charAt(i))
isNumber = 1;
}
So, the complete code for the isZIP function would look like this:
function isZIP(myNumber)
{
if (myNumber.length != 5) {return false;}
for (var i = 0; i < myNumber.length; i++)
{
isNumber = 0;
for (var j=0; j<10; j++) if
("" + j == myNumber.charAt(i)) isNumber = 1;
if (isNumber == 0) {return false;}
}
return true;
}
To check for a credit card number (Visa/MC), you would do the same thing
except check for sixteen digits instead of five.
function isCC(myNumber)
{
if (myNumber.length != 16) {return false;}
for (var i = 0; i < myNumber.length; i++)
{
isNumber = 0;
for (var j=0; j<10; j++) if
("" + j == myNumber.charAt(i)) isNumber = 1;
if (isNumber == 0) {return false;}
}
return true;
}
Next Page > Social Security Numbers > Page
1, 2, 3,
4, 5
 |