Solved

whats wrong with this code?

Posted on 2006-11-04
10
218 Views
Last Modified: 2013-12-03
Hello,
I have some javascript to validate an HTML form. It doesnt work gives me errors in FireFox like frm.name.value has no properties. Can someone please correct this script for me so I can see and learn what I am doing wrong. Here is the code I have:

<script type="text/javascript">
function validateForm(frm)
{
//validate the submitted form
alert('Validate.');
if (frm.freemag.selected == false)
{
      alert('You must choose your free magazine.');
      return false;
}
else if(frm.name.value.length == 0)
{
      alert('You must enter your name.');
      return false;
}
else if (frm.address.value.length == 0)
{
      alert('You must enter your address.');
      return false;
}
else if (frm.city.value.length == 0)
{
      alert('You must enter your city.');
      return false;
}
else if (frm.state.value.length == 0)
{
      alert('You must enter your state.');
      return false;
}
else if (frm.zip.value.length == 0)
{
      alert('You must enter your zip.');
      return false;
}
else if (frm.paytype.selected == false)
{
      alert('You must select your payment / card type.');
      return false;
}
else if (isMod10(frm.ccnum.value) == false)
{
      alert('Your card number is invalid.');
      return false;
}
else if ((frm.ccexpmonth.selected == false) || (frm.ccexpyear.selected == false))
{
      alert('Please complete your credit card expiration.');
      return false;
}
else
      return true;
}

function isMod10(num) {
    num = num.replace(/ |-/g, ""); // strip any spaces and dashes
    if(num.search(/\D/) > -1) return false; // check for non-digit characters in number
    if(parseInt(num) == 0) return false; // check if number consists of only zeroes
    var len = num.length; // assign number of digits
    if (len < 13) return false; // check if number is at least 13 digits
    var testNum = parseInt(num.charAt(len-1)); // initialize testNum with the check digit
    var tempNum;
    for (var i = len-2; i > 0; i=i-2) { //  begin mod 10 algorithm, starting with the next-to-last character
        tempNum = parseInt(num.charAt(i))*2;
        if (tempNum > 9) tempNum -= 9;
        testNum += tempNum;
        testNum += parseInt(num.charAt(i-1));
    }
    if (i == 0) {
        tempNum = parseInt(num.charAt(i))*2;
        if (tempNum > 9) tempNum -= 9
        testNum += tempNum;
    }
    return testNum % 10 == 0;
}
</script>


<form action="manager.cfm?where=processpayment" method=post onsubmit="return validateForm(this);">
<table>
<tr>
<TD COLSPAN=2 ROWSPAN=3 background=white align=center valign=top><table border=0 cellpadding=0 cellspacing=0>
            <tr>
            <td align=right style="font-family: arial; font-size: 15;">Name:</td><td colspan=3><input type=name size=20 maxlength=25></td>
            </tr>
            <tr>
            <td align=right style="font-family: arial; font-size: 15;">Address:</td><td colspan=3><input type=address size=25 maxlength=25></td>
            </tr>
            <tr>
            <td align=right style="font-family: arial; font-size: 15;">City:</td><td colspan=3><input type=city size=15 maxlength=15></td>
            </tr>
            <tr>
            <td align=right style="font-family: arial; font-size: 15;">State:</td><td style="font-family: arial; font-size: 16;"><input type=state size=2 maxlength=2></td><td style="font-family: arial; font-size: 15;" align=right>Zip:</td><td><input type=zip size=5 maxlength=5></td>
            </tr>
            <tr>
            <td align=right style="font-family: arial; font-size: 15;">Email:</td><td colspan=3><input type=email size=25></td>
            </tr>
            <tr>
            <td align=right colspan=4 style="font-family: arial; font-size: 15;"><hr size=1></td>
            </tr>
            <tr>
            <td align=right style="font-family: arial; font-size: 15;">Card Type:</td><td colspan=3><select name=paytype><option>Choose Payment Type</option><option value="pp">Paypal</option><option value="MC">Mastercard</option><option value="VI">Visa</option><option value="AM">American Express</option><option value="DS">Discover</option></select></td>
            </tr>
            <tr>
            <td align=right style="font-family: arial; font-size: 15;">CC#:</td><td colspan=3><input type=ccnum size=16 maxlength=16></td>
            </tr>
            <tr>
            <td align=right style="font-family: arial; font-size: 15;">Expiration:</td><td colspan=3><input type=ccexpmonth size=2 maxlength=2>/<input type=ccexpyear size=4 maxlength=4></td>
            </tr>
            </table>
            </TD>
</tr>
</table>

Worth 500 points.

Thanks,
Rick
0
Comment
Question by:richardsimnett
10 Comments
 
LVL 49

Expert Comment

by:Roonaan
Comment Utility
frm.name like frm.submit are kind of semi-reserver.

You can of course use frm.elements['name'], but you'd rather rename the field as frm.name is most often used to get the name property in <form name="myformname">

-r-
0
 
LVL 15

Accepted Solution

by:
bpmurray earned 500 total points
Comment Utility
Loads stuff rather flakey in this. First, it's always good to format your stuff so that you can actually read it :-) Next, you're making assumptions about the browser and how it address things. And you're referring to "name" as though it wasn't an attribute of the DOM node. And the input type= has a very restricted set of types.

Anyway, try this:

<html><head>
<script type="text/javascript">

// Return the object from the page
function getElement(elName) {
   if (document.getElementById) {
      return document.getElementById(elName);
   } else {
      return eval("document.all." + elName);
   }
}

function validateForm(frm)
{
   //validate the submitted form
   alert('Validate.');
   var obj = getElement("freemag");
   if (obj != null && obj.selected == false) {
     alert('You must choose your free magazine.');
     return false;
   }
   
   obj = getElement("yourname");
   if (obj != null && obj.value.length == 0) {
     alert('You must enter your name.');
     return false;
   }
   
   obj = getElement("address");
   if (obj != null && obj.value.length == 0) {
     alert('You must enter your address.');
     return false;
   }
   
   obj = getElement("city");
   if (obj != null && obj.value.length == 0) {
     alert('You must enter your city.');
     return false;
   }
   
   obj = getElement("state");
   if (obj != null && obj.value.length == 0) {
     alert('You must enter your state.');
     return false;
   }
   
   obj = getElement("zip");
   if (obj != null && obj.value.length == 0) {
     alert('You must enter your zip.');
     return false;
   }
   
   obj = getElement("paytype");
   if (obj != null && obj.options.selectedIndex == 0) {
     alert('You must select your payment / card type.');
     return false;
   }
   
   obj = getElement("ccnum");
   if (obj != null && obj.value.length == 0 || isMod10(obj.value) == false) {
     alert('Your card number is invalid.');
     return false;
   }
   
   obj = getElement("ccexpmonth");
   if (obj != null && (obj.value.length == 0 || obj.value > 12 || obj.value < 1)) {
     alert('Please complete your credit card expiration.');
     return false;
   }

   obj = getElement("ccexpyear");
   if (obj != null && (obj.value.length == 0 || obj.value < 06)) {
     alert('Please complete your credit card expiration.');
     return false;
   }
   return true;
}

function isMod10(num) {
    num = num.replace(/ |-/g, ""); // strip any spaces and dashes
    if(num.search(/\D/) > -1) return false; // check for non-digit characters in number
    if(parseInt(num) == 0) return false; // check if number consists of only zeroes
    var len = num.length; // assign number of digits
    if (len < 13) return false; // check if number is at least 13 digits
    var testNum = parseInt(num.charAt(len-1)); // initialize testNum with the check digit
    var tempNum;
    for (var i = len-2; i > 0; i=i-2) { //  begin mod 10 algorithm, starting with the next-to-last character
        tempNum = parseInt(num.charAt(i))*2;
        if (tempNum > 9) tempNum -= 9;
        testNum += tempNum;
        testNum += parseInt(num.charAt(i-1));
    }
    if (i == 0) {
        tempNum = parseInt(num.charAt(i))*2;
        if (tempNum > 9) tempNum -= 9
        testNum += tempNum;
    }
    return testNum % 10 == 0;
}
</script>
</head><body>

<form action="manager.cfm?where="processpayment"" method="post" onsubmit="return validateForm(this);">
   <table><tr><TD COLSPAN="2" ROWSPAN="3" background="white" align="center" valign="top">
       <table border="0" cellpadding="0" cellspacing="0">
          <tr>
             <td align="right" style="font-family: arial; font-size: 15;">Name:</td>
             <td colspan="3"><input type="text" id="yourname" name="yourname" size="20" maxlength="25"></td>
          </tr>
          <tr>
             <td align="right" style="font-family: arial; font-size: 15;">Address:</td>
             <td colspan="3"><input type="text" id="address" name="address" size="25" maxlength="25"></td>
          </tr>
          <tr>
             <td align="right" style="font-family: arial; font-size: 15;">City:</td>
             <td colspan="3"><input type="text" id="city" name="city" size="15" maxlength="15"></td>
          </tr>
          <tr>
             <td align="right" style="font-family: arial; font-size: 15;">State:</td>
             <td style="font-family: arial; font-size: 16;"><input type="text" id="state" name="state" size="2" maxlength="2"></td>
             <td style="font-family: arial; font-size: 15; text-align:right;">Zip:</td>
             <td><input type="text" id="zip" name="zip" size="5" maxlength="5"></td>
          </tr>
          <tr>
             <td align="right" style="font-family: arial; font-size: 15;">Email:</td>
             <td colspan="3"><input type="text" id="email" name="email" size="25"></td>
          </tr>
          <tr>
             <td align="right" colspan="4" style="font-family: arial; font-size: 15;"><hr size="1"></td>
          </tr>
          <tr>
             <td align="right" style="font-family: arial; font-size: 15;">Card Type:</td>
             <td colspan="3">
                <select id="paytype" name="paytype">
                   <option>Choose Payment Type</option>
                   <option value="pp">Paypal</option>
                   <option value="MC">Mastercard</option>
                   <option value="VI">Visa</option>
                   <option value="AM">American Express</option>
                   <option value="DS">Discover</option>
                </select>
             </td>
          </tr>
          <tr>
             <td align="right" style="font-family: arial; font-size: 15;">CC#:</td>
             <td colspan="3"><input type="text" id="ccnum" name="ccnum" size="16" maxlength="16"></td>
          </tr>
          <tr>
             <td align="right" style="font-family: arial; font-size: 15;">Expiration:</td>
             <td colspan="3"><input type="text" id="ccexpmonth" name="ccexpmonth" size="2" maxlength="2">/
                             <input type="text" id="ccexpyear" name="ccexpyear" size="4" maxlength="4">
             </td>
          </tr>
       </table>
   </TD></tr></table>
   <input type="submit" value="You forgot the submit button">
</body></html>

0
 

Author Comment

by:richardsimnett
Comment Utility
bpmurray,
Ok this thing seems to work except for one part... it does not properly verify that the freemag select box has an item selected. Can you fix this and I will award you the points.

THanks,
Rick
0
 
LVL 17

Expert Comment

by:gops1
Comment Utility
There is no freemag in your code
0
 

Author Comment

by:richardsimnett
Comment Utility
gops1,
freemag is outlined in the javascript posted in my original question. It is a multiple select box, but you are right it was overlooked in the html post.

Rick
0
What Security Threats Are You Missing?

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.

 
LVL 15

Expert Comment

by:bpmurray
Comment Utility
Actually freemag isn't anywhere here: that's why I put that code for its validation - I just didn't know what it was. The following should work, but if you post the HTML for it, I can verify that.

   var obj = getElement("freemag");
   if (obj != null && obj.options.selectedIndex == 0) {
     alert('You must choose your free magazine.');
     return false;
   }
0
 

Author Comment

by:richardsimnett
Comment Utility
bpmurray,
Here is the code for the select box... its pretty basic:

      <select name="freemag" multiple style="height: 200px; width: 290px;">

                  
                        <option value="40032">Alternative Press</option>
                  
                        <option value="43010">Amazin Magazine</option>
                  
                        <option value="2572">American Cheerleader</option>
                  
                        <option value="2172">American Legacy</option>
                  
                        <option value="192">American Photo</option>
                  
                        <option value="40977">Arthritis Today</option>

            </select>

Thanks,
Rick
0
 
LVL 15

Expert Comment

by:bpmurray
Comment Utility
OK, here are the changes you need:

1. The JavaScript to validate the freemag field - check that the selected item number is not -1:
  var obj = getElement("freemag");
   if (obj != null && obj.options.selectedindex < 0) {
 

2. The HTML for the freemag - include an id= attribute:
  <select name="freemag" id="freemag" multiple style="height: 200px; width: 290px;">
   
0
 

Author Comment

by:richardsimnett
Comment Utility
bpmurray,
Ok I finally got this working. Your code had incorrect logic operators in the IF statements. The &&'s should be ||'s and the comparisons needed to be adjusting accordingly. It all works perfectly now.

Thanks for the help.

Rick
0
 

Author Comment

by:richardsimnett
Comment Utility
Here is the code that I am now using for reference, If you would like to see the code in action please visit http://www.magazinerewardcenter.com and click on one of the magazine offers, the subsequent landing page has the form and javascript up and running.

Thanks,
Rick

// Return the object from the page
function getElement(elName) {
   if (document.getElementById) {
      return document.getElementById(elName);
   } else {
      return eval("document.all." + elName);
   }
}

function validateForm(frm)
{
   //validate the submitted form
   var obj = getElement("freemag");
   if (obj == null || obj.options.selectedIndex < 0) {
     alert('You must choose your free magazine.');
     return false;
   }

   obj = getElement("yourname");
   if ((obj == null) || (obj.value.split(" ").length <= 1) || (obj.value.length <= 0)) {
     alert('You must enter your name.');
     return false;
   }

   obj = getElement("address");
   if (obj == null || obj.value.split(" ").length < 2 || obj.value.length <= 0) {
     alert('You must enter your address.');
     return false;
   }

   obj = getElement("city");
   if (obj == null || obj.value.length <= 0) {
     alert('You must enter your city.');
     return false;
   }

   obj = getElement("state");
   if (obj == null || obj.options.selectedIndex <= 0) {
     alert('You must enter your state.');
     return false;
   }

   obj = getElement("zip");
   if (obj == null || obj.value.length < 5) {
     alert('You must enter your zip.');
     return false;
   }

   obj = getElement("email");
   if (obj == null || obj.value.length <= 0 || isValidEmail(obj.value) == false)
   {
               alert('You must enter a valid email address');
               return false;
   }

      obj = getElement("paytype");
         if (obj == null || obj.options.selectedIndex <= 0) {
     alert('You must select your payment / card type.');
     return false;
         }

   obj = getElement("ccnum");
   if (obj == null || obj.value.length <= 0 || isMod10(obj.value) == false) {
     alert('Your card number is invalid.');
     return false;
   }

   obj = getElement("ccexpmonth");
   if (obj == null || obj.options.selectedIndex <= 0) {
     alert('Please complete your credit card expiration month.');
     return false;
   }

   obj = getElement("ccexpyear");
   if (obj == null || obj.options.selectedIndex <= 0) {
     alert('Please complete your credit card expiration year.');
     return false;
   }

   return true;
}

0

Featured Post

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

Join & Write a Comment

When you need to keep track of a simple list of numbers or strings, the Array object is your most direct tool.  As we saw in my earlier EE Article (http://www.experts-exchange.com/A_3488.html), typical array handling might look like this: (CODE) B…
Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
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…

744 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

14 Experts available now in Live!

Get 1:1 Help Now