Page 1 of 1

Form Validation Fails, but Form Still Submitted:

Posted: Thu Dec 10, 2009 1:57 pm
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.

Re: Form Validation Fails, but Form Still Submitted:

Posted: Thu Dec 10, 2009 3:05 pm
by kaszu

Code: Select all

onsubmit="return validateForm()"
change to

Code: Select all

onsubmit="return validateForm(this)"

Re: Form Validation Fails, but Form Still Submitted:

Posted: Thu Dec 10, 2009 3:09 pm
by shortaug
I do that, and then it runs validateForm twice and still submits the form.

Re: Form Validation Fails, but Form Still Submitted:

Posted: Thu Dec 10, 2009 4:51 pm
by shortaug
Simple mistake, as usual..

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

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