Skip to content Skip to sidebar Skip to footer

Php Form Submits Before Javascript Validation

I'm having a somewhat common problem of getting my form to validate before submission. I've tried several variations on the same theme and with no dice: at best I could get nothing

Solution 1:

You're making it to complex.

JavaScript:

functionvalidateForm() {
    var x = document.forms["savegameform"]["username"].value;
    if (x == null || x == "") {
        document.getElementByID("JSError").innerHTML = "Error: Please enter a name."; 
        returnfalse;
    } else { returntrue; }
}

HTML:

<formname="savegameform"method="post"action="submitsave.php"onSubmit="return validateForm()"><p><spanclass="formline">Name: </span><inputtype="text"name="username"size="25"><br />
//More of the form
<inputtype="submit"name="submit"value="Submit"><spanid="JSError">Test.</span></p></form>

Solution 2:

Your validation works fine, but because you are trying to

document.getElementByID("JSError").innerHTML

instead of

document.getElementById("JSError").innerHTML

JS throws an error and never reaches your "return false". You can easily see this, when you use your browsers console output. (In firefox and chrome press F12).

Example fiddle: http://jsfiddle.net/6tFcw/

Solution 3:

1st solution - using input[type=submit]

<!-- HTML -->
<inputtype="submit"name="submit"value="Submit"onclick="return validateForm();" />// JavaScriptfunctionvalidateForm(){
    var target = document.getElementById("name"); // for instanceif(target.value.length === 0){ 
        alert("Name is required");
        returnfalse;
    }
    // all right; submit the formreturntrue;
}

2nd solution - using input[type=button]

<!-- html -->
<inputtype="button"name="submit"id="submit"value="Submit" />// JavaScriptwindow.onload = function(){
    var target = document.getElementById("name");
    document.getElementById("submit").onclick = function(){    
        if(target.value.length === 0){ 
            alert("Name is required");
        }else{
            // all right; submit the form
            form.submit();
        }
    };
};

Post a Comment for "Php Form Submits Before Javascript Validation"