PHP表单在Javascript验证之前提交 [英] 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 to submit, but usually my form just ignores codes and submits anyway.
有机会我错过了一些小事,但我会很感激任何帮助!基本上只是试图确保这里的名字不是空的(回归真实;是毫无意义的IIRC,但我变得绝望哈哈)。一旦我可以得到一些基本的验证水平,就可以归结为JS编码的更复杂的演习,所以这应该足够好,我希望。谢谢!
Chances are I'm missing something small but I'd appreciate any help! Essentially just trying to make sure the name isn't empty here (return true; is pointless IIRC but I was getting desperate haha). Once I can get some basic level of validation down it just comes down to coding the JS for more complicated maneuvers so this should be good enough, i hope. Thanks!
<script>
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;
}
alert("Bla");
}
</script>
<form name="savegameform" method="post" action="submitsave.php" onSubmit="return validateForm(); return false;"><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>
推荐答案
1st solution - using input [type = submit]
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;
}
第二种解决方案 - 使用输入[type = button]
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();
}
};
};
这篇关于PHP表单在Javascript验证之前提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!