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:

function validateForm() {
    var x = document.forms["savegameform"]["username"].value;
    if (x == null || x == "") {
        document.getElementByID("JSError").innerHTML = "Error: Please enter a name."; 
        return false;
    } else { return true; }
}

HTML:

<form name="savegameform" method="post" action="submitsave.php" onSubmit="return validateForm()"><p>
<span class="formline">Name: </span><input type="text" name="username" size="25"><br />
//More of the form
<input type="submit" name="submit" value="Submit">

<span id="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 -->
<input type="submit" name="submit" value="Submit" onclick="return validateForm();" />

// JavaScript
function validateForm(){
    var target = document.getElementById("name"); // for instance
    if(target.value.length === 0){ 
        alert("Name is required");
        return false;
    }
    // all right; submit the form
    return true;
}

2nd solution - using input[type=button]

<!-- html -->
<input type="button" name="submit" id="submit" value="Submit" />

// JavaScript
window.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"