Form Validation Fails, but Form Still Submitted:

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
shortaug
Forum Newbie
Posts: 13
Joined: Wed May 13, 2009 6:11 pm

Form Validation Fails, but Form Still Submitted:

Post by shortaug »

My basic code is below, and yes I intend to expand upon the validation capabilities.

Code: Select all

 
<script type="text/javascript">
     function validateField(field, error) {
        if (field.value == "") {
            alert(error);
            return false;
        } else {
            return true;
        }
    }
 
    function validateForm(form) {
        if (!validateField(form.name, "Please enter your name.")) {
            name.focus();
            return false;
        }
        if (!validateField(form.kit, "Please select a kit.")) {
            return false;
        }
        if (!validateField(form.days, "Please enter the number of days you wish to hire for.")) {
            days.focus();
            return false;
        }
        return true;
    }
</script>
 
<form action="http://do.this.there/do_it.pl" onsubmit="return validateForm()" method="get" >
 
 
In testing, the appropriate alert box always pops up, but after I click 'ok', the form is submitted. I am using Firefox and Safari (latest of both) on a Mac OS 10.6. I can't figure out why.
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: Form Validation Fails, but Form Still Submitted:

Post by kaszu »

Code: Select all

onsubmit="return validateForm()"
change to

Code: Select all

onsubmit="return validateForm(this)"
shortaug
Forum Newbie
Posts: 13
Joined: Wed May 13, 2009 6:11 pm

Re: Form Validation Fails, but Form Still Submitted:

Post by shortaug »

I do that, and then it runs validateForm twice and still submits the form.
shortaug
Forum Newbie
Posts: 13
Joined: Wed May 13, 2009 6:11 pm

Re: Form Validation Fails, but Form Still Submitted:

Post by shortaug »

Simple mistake, as usual..

name.focus() and days.focus() should be:

form.name.focus() and form.days.focus().
Post Reply