-5

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>
Mat
  • 202,337
  • 40
  • 393
  • 406
rachel
  • 225
  • 2
  • 5
  • 16
  • 2
    There must be a problem with your validate function which needs to be fixed. We'd need to see it to help you with that. "Also this html is being included from other html." doesn't make sense? – Dale K Jan 12 '12 at 08:00
  • its interchange so the main page includes this page.. – rachel Jan 12 '12 at 08:03
  • I need a little more information. does your button activate a form.submit() or is it just a input type=submit button? – Guidhouse Jan 12 '12 at 08:04
  • Show us your actual validate function. If this one that you wrote in your question is the actual one, then there's no wonder that it doesn't work. It has invalid code in the first place. – Robert Koritnik Jan 12 '12 at 08:06
  • no my button does not activate a form.submit()... – rachel Jan 12 '12 at 08:06
  • i have edited my validation function – rachel Jan 12 '12 at 08:08
  • 2
    Your `input` submit button should as well be part of your form shouldn't it? **First of all @rachel**: If you'd like this community to put their effort into answering your questions, you should first put your effort to write good questions with relevant code. – Robert Koritnik Jan 12 '12 at 08:08
  • 3
    I refuse to help when OP doesn't even care enough to indent the code properly – Ruan Mendes Jan 12 '12 at 08:09
  • 2
    @rachel: your `validate_outofstockform` doesn't get called because in your `form` element you're referencing a different function called `validate`... Or Are you just being sloppy and providing some invalid code so we can imagine whatever we'd like... Which is a NO GO to ask a questions. You'll end up on your own... – Robert Koritnik Jan 12 '12 at 08:10
  • I agree with @JuanMendes – Kumar Jan 12 '12 at 08:15
  • I just thought pasting whole code would be irrelevant..that is why i pasted just the main layout of my code..sorry will keep that in mind. – rachel Jan 12 '12 at 08:20
  • 2
    Well the code has so many problems. You show code with name frm, yet you have outofstock_form object. What you have shown is complete rubbish. – Myforwik Jan 12 '12 at 08:36
  • 2
    @rachel: Are you a [Help Vampire](http://slash7.com/2006/12/22/vampires/)? – Peter-Paul van Gemerden Jan 12 '12 at 09:18
  • 3
    Step through the code with Firebug and see what it actually does. – Dale K Jan 12 '12 at 09:20
  • @PPvG that was really funny..Help Vampire. But this question was not to cause trouble or irritate someone. – rachel Jan 12 '12 at 09:27
  • @RobertKoritnik can you plz tell me now what is going wrong with this code – rachel Jan 12 '12 at 09:31
  • 1
    @rachel: you should [read the article](http://slash7.com/2006/12/22/vampires/). It's well-written and quite interresting. I really think it could help you to ask better, more constructive questions. And avoid all the negative comments; I can't image those are pleasant to get... So [read it!](http://slash7.com/2006/12/22/vampires/) **:-)** – Peter-Paul van Gemerden Jan 12 '12 at 09:33
  • @PPvG yes have read that already..so plz stop fighting now.. :( – rachel Jan 12 '12 at 09:36
  • 1
    @rachel: fighting? I'm sorry if I caused you offense. I'm just trying to **help**... In fact, you may have noticed that I suggested an edit to your question? You seem to have ignored it, but I spent 5 minutes improving your question, making the code more readable, et cetera. **And** I posted an answer. – Peter-Paul van Gemerden Jan 12 '12 at 09:37
  • 1
    Rachel, it's not funny, read the article with some thought about what you could be doing differently. If this is your first JavaScript form, say so. Try to pare down the problem to a single question. @PPvG thanks for the link, and your reply. – tripleee Jan 12 '12 at 09:41
  • 1
    @PPvG: My changes were also re-changed back to whatever... Rachel should keep valuable changes and not keep changing question title to grammatically invalid test. We all tried improving here question bit by bit but she kept changing our changes back or extended confusion. – Robert Koritnik Jan 12 '12 at 09:55
  • @rachel: could you please accept my suggested changes? I've reformatted the code so it's more readable. (Just in case: **[here it is on JS Bin](http://jsbin.com/emekic/edit#html)**.) – Peter-Paul van Gemerden Jan 12 '12 at 09:59
  • 1
    Thanks have accepted your changes – rachel Jan 12 '12 at 10:13
  • possible duplicate of [Validate email address in JavaScript?](http://stackoverflow.com/questions/46155/validate-email-address-in-javascript) – Superman2013 Mar 26 '14 at 22:56

3 Answers3

2

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

Tadeck
  • 132,510
  • 28
  • 152
  • 198
1

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.
Community
  • 1
  • 1
1

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.

Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
  • Thanks will do that. I don have much experience with java script. – rachel Jan 12 '12 at 09:46
  • 1
    @rachel: When having problems with your code, just try a simplified proof-of-concept example so you can see whether it works. After it does fully implement your actual code. but since these kind of manipulations/checking/validations work you must have a bug in your code. **Debugging will definitely solve this.** – Robert Koritnik Jan 12 '12 at 09:49