我想,我的javascript上出现了验证问题。它仍然在表单无效时提交。具体来说,当用户输入的长度超过10个字符时,它仍然会将表单提交到数据库中,同时它应该显示警告。这是脚本:
<script type="text/javascript">
function validateForm()
{
var numericExpression = /^[0-9]+$/;
var a=document.forms["purchaseform"]["no"].value;
var b=document.forms["purchaseform"]["qty"].value;
if (a==null || a=="")
{
alert("Form number must be filled out");
return false;
}
if(a.match(numericExpression))
{
return true;
}
else
{
alert("Form number must be filled with numbers only");
return false;
}
if(a.length > 10) //i got a problem with this one i think
{
alert("Form number must not be greater than 10 character length");
return false;
}
if (b==null || b=="")
{
alert("Quantity must be filled out");
return false;
}
if(b.match(numericExpression))
{
return true;
}
else
{
alert("Quantity must be filled with numbers only");
return false;
}
}
</script>
以下是表格摘要:
<form name="purchaseform" method="post" onsubmit="return validateForm()" action="submitpurchaseadmin.php">
<table>
<tr>
<td>Form number</td>
<td><input type="text" name="no"></td>
</tr>
<tr>
<td>Category</td>
<td>
<select id="cat" name="cat">
</select>
</td>
</tr>
<tr>
<td>Item</td>
<td>
<select id="item" name="item">
</select>
</td>
</tr>
<tr>
<td>Quantity</td>
<td><input type="text" name="qty"></td>
</tr>
<tr>
<td>Date</td>
<td><input type="text" name="date" value="<?php echo date("d-m-Y"); ?>"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="submit" value="Save"></td>
</tr>
</table>
</form>
答案 0 :(得分:1)
为这些输入添加ID并执行
function validateForm() {
var a = document.getElementById("no").value;
var b = document.getElementById("qty").value;
if (!a.length) {
alert("Form number must be filled out");
return false;
}else if (!a.match(/^[0-9]+$/)) {
alert("Form number must be filled with numbers only");
return false;
}else if (a.length > 10) {
alert("Form number must not be greater than 10 character length");
return false;
}else if (!b.length) {
alert("Quantity must be filled out");
return false;
}else if (!b.match(/^[0-9]+$/)) {
alert("Quantity must be filled with numbers only");
return false;
}
}
答案 1 :(得分:0)
onsubmit
不会自动阻止表单提交,您需要在onsubmit函数中使用preventDefault
。
见这里:
onsubmit method doesn't stop submit
值得注意的是 - 虽然Adeneo的修复程序解决了空白名称和数量,但它似乎没有提醒a
的长度。
答案 2 :(得分:0)
问题可能就在这里:if(a.match(numericExpression))
,当用户输入的长度超过10个字符时,此if语句也将返回true。