Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Validate number length 6

Status
Not open for further replies.

fedtrain

Instructor
Jun 23, 2004
142
US
Hello all,
I found this bit of code by AtomicChip:
Code:
If you're looking for validation for Zip code (US), try the following:

function Validate(val)
{
    var regEx = /[0-9]{5}/;
    if(regEx.test(val))
    {
    alert('Valid Zip Code');
    }
    else
    {
    alert('Invalid Zip Code');
    }
}

Can someone expound on what the string for the variable 'regEx' means/is doing?

I need to validate a number field on my form and I need to limit it to 9 or 10 digits. Anything less or more and it needs to throw the alert "Please enter a valid number."

Dave

"Credit belongs to the man who is actually in the arena - T.Roosevelt
 

I would use this:

Code:
if (numberStr.length < 9 || numberStr.length > 10) alert('Incorrect!');

Where "numberStr" is the number string entered.

Hope this helps,
Dan
 
The numbers inside the square brackets are the allowed character set (0-9 in this case). The squiggly brackets (what the hell are those things called anyway?) set the number of occurrences of the previous item (5 in this case).

You should have set beginning(^) and end($) too though, otherwise they could enter nonsense like aaa12345aaaa and it would still match the numbers in the middle.

9 - 10 would be something like var regEx = /^[0-9]{9,10}$/;

HTH.
 
Thanks BillyRay for your input, I ended up doing it that way anyway.

Also thanks to theboy for the explaination and the modification of the code. I just couldn't figure out how to shoe horn it into the validations I was already running so I went the easy way for now.

Any info on why the /'s are used?

Thanks again.
Dave

"Credit belongs to the man who is actually in the arena - T.Roosevelt
 
fedtrain,

If you're interested in learning the terminology for using regular expressions you might wanna check out these sites. Regex is very powerful when you learn how to use them efficiently and often times can knock multiple lines of code into only one line.

Explanations:

General regex sites

-kaht

banghead.gif
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top