Javascript form validation isn't working

1.6k views Asked by At

I'm writing a form validation script in JavaScript. When the form is submitted, I want it to be validated before going to the next page.

This page is being called from another page using Perl Interchange. Validation is performed for the three fields on the form.


Update: here is the full code:

    <FORM  ACTION="[process]" name="outofstock_form" METHOD=POST onsubmit="return      validate_outofstockform();" >
    <INPUT TYPE=hidden NAME="mv_todo"  VALUE="return">
    <INPUT TYPE=hidden NAME="mv_nextpage" VALUE="outofstock_wish_submit">
    <INPUT TYPE=hidden VALUE="[perl scratch session]$which_search;[/perl]" NAME="search_key">

    <script type=javascript>
        function validate_outofstockform() {
            var m = document.forms["outofstock_form"]["email"].value
            var e = document.outofstock_form.email.value
            var f = document.forms["outofstock_form"]["name"].value
            var p = documnet.forms["outofstock_form"]["wish_product"].value

            var atpos = e.indexOf("@");
            var dotpos = e.lastIndexOf(".");

            if (document.outofstock_form.email.value == "") {
                alert("The Email field is required.");
                return false;
            }
            if (document.outofstock_form.name.value == "") {
                alert("The Name field is required.");
                return false;
            }
            if (document.outofstock_form.wish_product.value == "") {
                alert("The Product field is required.");
                return false;
            }
            if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= e.length) {
                alert("Please enter a valid e-mail address");
                return false;
            }

            if (f == null || f == "" || f == "First Name") {
                alert("Please enter your first name");
                return false;
            }
            if (p == null || p == "" || p == "Product") {
                alert("Please enter your first name");
                return false;
            }
            return false;
        }
    </script>

    <br/>
    *Fields in bold are required.<br/>

    <table cellpadding="1" cellspacing="5" width="360px" border="0">
        <tr>
            <td><b>Name:</b></td>
            <td>
                <input type="text" id="name" name="name" size="40">
            </td>
        </tr>
        <tr>
            <td><b>E-mail:</b></td>
            <td>
                <input type="text" id="email" name="email" size="40">
            </td>
        </tr>
        <tr>
            <td>Phone:</td>
            <td>
                <input type="text" name="phone" size="40">
            </td>
        </tr>
        <tr>
            <td> State/ Province:</td>
            <td>[include pages/ord/widget_state.html]</td>
        </tr>
        <tr>
            <td > Zip/Postal Code:</td>
            <td><INPUT TYPE="text" NAME="zip" VALUE="" size="40" maxlength="10"></td>
        </tr>

        <br/>

        <tr>
            <td valign="bottom">Country:</td>
            <td>[include pages/ord/widget_country_s.html]</td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
        </tr>
        <tr>
            <td>Salesperson:</td>
            <td align=left colspan=2>
                <SELECT NAME="salesrep" class="field">
                    <OPTION VALUE="WEB">(Optional)
                    [query list=1 prefix=s sql="SELECT id AS username, real_name AS disp_name, everest_id AS int_id FROM employee WHERE sales_ddown = 'Y' AND everest_id != '' ORDER BY real_name"]
                    <OPTION VALUE="[s-param int_id]"[calc]'[value salesrep]' eq '[s-param int_id]' ? 'selected' : '';[/calc]>[s-param disp_name]
                    [/query]

                </SELECT>
            </td>    

            <INPUT TYPE=hidden NAME="salesperson" VALUE="[s-param username]">
            [perl values scratch]
            $Scratch->{salesperson} = q{[s-param username]};
            [perl]   

        <tr>
            <td colspan="2">
            Provide us with the product you are looking for, or the brand and product type
            of interest and we will inform you if we find a match.
            </td>
            <td></td>
        </tr>

        <tr>
            <td><b>Product:</b></td>
            <td>
                <input type="text" id="wish_product" name="wish_product" size="40" value="">
            </td>
        </tr>
        <tr>
            <td>Item Description:</td>
            <td>
            <textarea name="wish_descrip" rows="2" cols="40"></textarea>
            </td>
        </tr>

        <tr>

        <tr>
            <td>Brand/Manufacturer Preference:</td>
            <td><input type="text" name="wish_man" size="40"></td>
        </tr>
        <tr>
            <td>Product Category :</td>
            <td>
            <select name="wish_cat">
            <option value="" selected>Any Category</option>
            [include pages/CATLIST.html]
            </select>
            </td>
        </tr>
        <tr>
            <td>Is this for a business?:</td>
            <td>
            <input type="radio" name="option" value="Yes"> Yes
            <input type="radio" name="option" value="No"> No<br>
            </td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
        </tr>
        <tr>
            <td colspan="2"><font size="0px">
            We do not sell, rent or otherwise share your information with anyone.<br/>
            </font>
            </td>
            <td></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>
            <input type="submit" name="Submit" value="Submit" class="button">
            </td>
        </tr>

    </table>

</form>
3

There are 3 answers

1
Tadeck On

Make your JavaScript valid (remove part with multiple dashes) and make it return false to avoid sending the form.

0
Peter-Paul van Gemerden On

It's hard to tell what exactly is causing the problem, because there are several errors in your code.

A couple of pointers:

  • You're referencing document.outofstock_form, while the form's name is frm.
  • <//code table> is not valid HTML. Remove it or replace it with an HTML comment (e.g.: <!-- table code: -->).
  • It's more common to use a regular expression (search here on SO) to validate form input.
  • If you're sending the input to a server, perform validation on the server as well. Never trust input from the browser.
  • You never open the <tr> (presumably a copy-paste error).

And finally, but most importantly:

  • Always look at your browser's JavaScript error console first. This must be your starting point when debugging JavaScript code. It can help you find the problem and if it doesn't, it can help others help you.
  • Read How to Ask.
2
Robert Koritnik On

Have you debugged your code?

Use tools like Firebug to debug your scripts. Put a breakpoint in the first line of your validation function and then debug it step by step. You will eventually get to the line that's causing your problems.

A suggestion of how to improve your validator

But apart from debugging I would do validation differently. Instead of checking every single aspect of individual fields I'd rather just add a custom attribute to those inputs that need validation and just check whether they match or not. If any fails inform your user about non-valid field...

<input name="SomeName"
       validation-expression=".+"
       display-name="Required text field"
       type="text" />

Using libraries like jQuery would be even more helpful when working with such data because it would be much easier to enumerate these elements and work with their data... I would of course warmly suggest you use jQuery anyway because it will make your code much more cross-browser. It's a simple library with short learning curve but huge benefits.

But using those special attributes would make your validator function universal so it could be used with any element and on any page. All you'd have to do is to put particular validation attributes to your elements.

Just a suggestion of course.