Solved

javascript zip code validation

Posted on 2006-07-03
15
413 Views
Last Modified: 2008-01-09
Can anyone help?  I need to get this funciton to work to not allow letters.

function validateZip(zip)
{
str = zip.value;
nr = parseInt(str);
l = str.length;  
if (nr != NaN && nr.toString().length == l && l <= 9)
{
}
else
{
alert('Invalid Zip Code.  Please re-enter.');
zip.focus();
}
}
0
Comment
Question by:meaar
  • 6
  • 6
  • 3
15 Comments
 
LVL 36

Expert Comment

by:Zyloch
ID: 17033595
Hi meaar,

Maybe you mean:

if (isNaN(nr) && l > 9)
{
    alert('Invalid!');
}

although zip codes are either 5 or 9 (not in between) as far as I know.

Of course, you can also use regular expressions, such as:

if (!zip.value.match(/^[d]{5,9}/))
{
    alert('Invalid!');
}

Regards,
Ted
0
 

Author Comment

by:meaar
ID: 17033684
Hi Ted,

I included the full code as well as your regex code.  I am not noticing an an alert when I type in a letter for the zip field.  I lowered my security thinking that was it, but that did not help.  I am noticing that there was an error on the page, but no alert.  Any ideas?  Also it would be nice to also add this zipcode validation to the formvalidation.  

<html>
<head>

<style type="text/css">
h1,h2,h3,h4,h5,h6
{
color: black
}
</style>

<script type="text/javascript">

function validateZip(zip)
{
str = zip.value;
nr = parseInt(str);
l = str.length;
if (!zip.value.match(/^[d]{5,9}/))
{
    alert('Invalid!');
}
}
 

function stripNumber(number)
{
var number = number.replace(/[\(\)\- ,\a-zA-Z]/g,"");
return number
}

function emptyvalidation(entered, alertbox)
{
with (entered)
{
if (value==null || value=="")
{if (alertbox!="") {alert(alertbox);} return false;}
else {return true;}
}
}

function formvalidation(thisform)
{
with (thisform)
{
if (emptyvalidation(firstName,"Please enter your First Name")==false) {firstName.focus(); return false;};
if (emptyvalidation(lastName,"Please enter your Last Name")==false) {lastName.focus(); return false;};
if (emptyvalidation(address,"Please enter your Address")==false) {address.focus(); return false;};
if (emptyvalidation(city,"Please enter your City")==false) {city.focus(); return false;};
if (emptyvalidation(zipCode,"Please enter your Zip Code")==false) {zipCode.focus(); return false;};
if (emptyvalidation(areaCode,"Please enter your Area Code")==false) {areaCode.focus(); return false;};
if (emptyvalidation(phone,"Please enter your Phone Number")==false) {phone.focus(); return false;};
if (emptyvalidation(birthDay,"Please enter your Birthdate")==false) {birthDay.focus(); return false;};
if (emptyvalidation(cardNum,"Please enter your Credit Card Number")==false) {cardNum.focus(); return false;};
if (emptyvalidation(cardExpMonth,"Please enter your Credit Card Expiration Month")==false) {cardExpMonth.focus(); return

false;};
if (emptyvalidation(cardExpYear,"Please enter your Credit Card Expiration Year")==false) {cardExpYear.focus(); return

false;};
}
}
</script>
</head>

<body>
<h3 align="center">Please Fill Out the Form</h3>

<div align="center"><center>
<form onsubmit="return formvalidation(this)" action="MAILTO:meaar@email.uophx.edu" method="post" enctype="text/plain">
  <div align="center"><center><table border="1">
    <tr>
      <td align="right" bgcolor="#C0C0C0"><font color="#000000">First Name:</font></td>
      <td><div align="left"><p><input type="text" name="firstName" size="30"
    </tr>
    <tr>
      <td align="right" bgcolor="#C0C0C0"><font color="#000000">Last Name:</font></td>
      <td><div align="left"><p><input type="text" name="lastName" size="30"
    </tr>    
    <tr>
      <td align="right" bgcolor="#C0C0C0"><font color="#000000">Address:</font></td>
      <td><div align="left"><p><input type="text" name="address" size="30"
    </tr>
    <tr>
      <td align="right" bgcolor="#C0C0C0"><font color="#000000">City:</font></td>
      <td><div align="left"><p><input type="text" name="city" size="30"
    </tr>
   <tr>
      <td align="right" bgcolor="#C0C0C0"><font color="#000000">State:</font></td>
      <td><div align="left"><select name="state" size="1">
            <option value="Alabama">AL
            <option value="Alaska">AK
            <option value="Arizona">AS
            <option value="Arkansas">AR
            <option value="California">CA
            <option value="Colorado">CO
                <option value="Connecticut">CT
            <option value="Deleware">DE
            <option value="District_of_Columbia">DC
            <option value="Florida">GA
            <option value="Hawaii">HI
            <option value="Idaho">ID
            <option value="Illinois">IL
                <option value="Indiana">IN
            <option value="Iowa">IA
            <option value="Kansas">KS
            <option value="Kentucky">KY
            <option value="Louisiana">LA
            <option value="Maine">ME
            <option value="Massachusetts">MA
                <option value="Michigan">MI
            <option value="Minnesota">MN
            <option value="Mississippi">MS
            <option value="Missouri">MO
            <option value="Montana">MT
            <option value="Nebraska">NE
            <option value="Nevada">NV
                <option value="New_Hampshire">NH
            <option value="New_Jersey">NJ
            <option value="New_Mexico">NM
            <option value="New_York">NY
            <option value="North_Carolina">NC
            <option value="North_Dakota">ND
            <option value="Ohio">OH
                <option value="Oklahoma">OK
            <option value="Oregon">OR
            <option value="Pennsylvania">PA
            <option value="Rhose_Island">RI
            <option value="South_Carolina">SC
            <option value="South_Dakota">SD
            <option value="Tennessee">TN
            <option value="Texas">TX
            <option value="Utah">UT
            <option value="Vermont">VT
            <option value="Virginia">VA
            <option value="Washington">WA
            <option value="West_Virginia">WV
            <option value="Wisconsin">WI
            <option value="Wyoming">WY
            
      </select>
    </tr>
   <tr>
      <td align="right" bgcolor="#C0C0C0"><font color="#000000">Zip:</font></td>
      <td><div align="left"><p><input type="text" name="zipCode" size="30" onChange="validateZip(this.value)">
   </tr>
   <tr>
      <td align="right" bgcolor="#C0C0C0"><font color="#000000">Area Code:</font></td>
      <td><div align="left"><p><input onblur="this.value=stripNumber(this.value)" name="areaCode" size="30">
   </tr>
   <tr>
      <td align="right" bgcolor="#C0C0C0"><font color="#000000">Phone Number:</font></td>
      <td><div align="left"><p><input onblur="this.value=stripNumber(this.value)" name="phone" size="30"></td>
   </tr>
   <tr>
      <td align="right" bgcolor="#C0C0C0"><font color="#000000">Date of Birth:</font></td>
      <td><div align="left"><p><input type="text" name="birthDay" size="30">
    </tr>
    <tr>
      <td align="right" bgcolor="#C0C0C0"><font color="#000000">Credit Card Type:</font></td>
      <td><div align="left">
            <input type="radio" checked="checked" name="cardType" value="amex"> American Express <br>
            <input type="radio" checked="checked" name="cardType" value="chase"> Chase <br>
            <input type="radio" checked="checked" name="cardType" value="mastercard"> MasterCard <br>
            <input type="radio" checked="checked" name="cardType" value="visa"> Visa <br>
    </tr>
    <tr>
      <td align="right" bgcolor="#C0C0C0"><font color="#000000">Credit Card Number:</font></td>
      <td><div align="left"><p><input type="text" name="cardNum" size="30"
    </tr>
    <tr>
      <td align="right" bgcolor="#C0C0C0"><font color="#000000">Credit Card Expiration Month: (01 for January)</font></td>
      <td><div align="left"><p><input type="text" name="cardExpMonth" size="30"
    </tr>
    <tr>
      <td align="right" bgcolor="#C0C0C0"><font color="#000000">Credit Card Expiration Year: (4 digits, e.g.,

1999)</font></td>
      <td><div align="left"><p><input type="text" name="cardExpYear" size="30"
    </tr>
    <tr>
      <td align="right" bgcolor="#C0C0C0" colspan="2"><font color="#000000"><div align="center"><center><p><input
      type="submit" value="Submit" name="Button1"></font></td>
    </tr>
  </table>
  </center></div>
</form>
</body>
</html>
0
 
LVL 36

Expert Comment

by:Zyloch
ID: 17033700
Perhaps:

function validateZip(zip)
{
    zip.value = zip.value.replace(/[^d]/g, '');    //strip field of all letters
    var zip_len = zip.value.toString.length;
    if (zip_len != 5 && zip_len != 9)
    {
        zip.value = '';   //clear field
        zip.focus();
    }
}

I do not know how you want to handle an error, since it is on onblur(). Do you want it to alert?

Ted
0
 

Author Comment

by:meaar
ID: 17033728
Yes, an alert would be good.  I believe I have the zipcode onChange.  
0
 
LVL 36

Expert Comment

by:Zyloch
ID: 17033745
meaar,

I think this should work:

function validateZip(zip)
{
    var zip_len = zip.value.toString().length;
    if (zip_len != 5 && zip_len != 9)
    {
        alert('Your zip code must be either 5 or 9 digits long!');
        zip.select();
        return false;
    }

    if (zip.match(/[^d]/))
    {
        alert('Your zip field must only contain digits!');
        zip.select();
        return false;
    }
}

}


Ted
0
 

Author Comment

by:meaar
ID: 17033789
Almost there.  The code does not seem to get past the first if.  It appears to accept, "aaaaa".   Ted, thanks for the quick response. ;)
0
 
LVL 36

Accepted Solution

by:
Zyloch earned 500 total points
ID: 17033801
Try adding this as well:

onkeyup="this.value = this.value.replace(/[^d]/g, '');"
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:meaar
ID: 17033839
Did you want me to change the onChange to onkeyup?  If yes, that does not seem to work.  It seems to delete any entry I add to that zip field.  
0
 
LVL 36

Expert Comment

by:Zyloch
ID: 17033842
No, just add it to the field.
0
 

Author Comment

by:meaar
ID: 17033987
I did not use what was suggested exactly, but I got some good ideas so I will give you the points.  Thanks Ted for your help and quick response.  
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 17034132
Please have a look at this: http:/help.jsp#hi73
0
 

Author Comment

by:meaar
ID: 17034145
Hmmm.  I didn't think the, "average" score I gave would give a, "C" grade.  Can I modify the grade Zvonko?  I think a a B is more appropriate.  Sorry Ted.  
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 17034203
You can easy let modify the grade.
But allow me one more statement: grade A does not cost you more then grade B ;-)
The upper help section does show the site owners view of grading.
But the Experts like Ted offer their free time to help others to solve their technical problems and learn new stuff. So you as asker do nor realy decide how good expert an Expert is. All you can do is to say ThankYou if his/her efforts did support you. But of course only if he/she realy did help you and the posting was not absolutely nonsense and waste of your and his time.
To ask for grade change you can post a request here: http:/Community_Support/askQuestion.jsp

Thanks for your understanding.

0
 
LVL 36

Expert Comment

by:Zyloch
ID: 17037912
Ah, it's alright in the end :-D, as long as I helped out. But thank you very much for supporting me, Zvonko.

Ted
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 17038510
You are welcome. And I see it like that new members do not know it and need someone to tell them.
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now