你可以试试这个并进行相应的定制 | 演示
只需在验证函数中传递表单(this),它将检查所有文本框是否为空,您可以根据自己的使用进行修改
<form name="addcust" method="POST" action="insrtCustomer.php" id="form1" onsubmit="return validate(this)">
<table>
<tr>
<td>Customer Name</td>
<td><input type="text" name="name" id="name"><label id="message"></label></td>
<td>City</td><td><input type="text" name="city" maxlength="25"></td>
</tr>
<tr>
<td>State</td><td><input type="text" name="state" maxlength="25"></td>
</tr>
</table>
<input type="submit" value="submit">
</form>
Javascript
function validate(dis)
{
var ele = dis.getElementsByTagName("input");
for(var i=0;i<ele.length;i++)
{
if(ele[i].getAttribute("type") == "text")
{
if(ele[i].value == "")
{
alert(ele[i].getAttribute('name')+" is required feild");
ele[i].focus();
return false;
}
}
// you can check for radio and checkboxes
//eg : if(ele[i].getAttribute("type") == "radio")
// {
// Your code here
// }
}
return true; // to prevent from form submission use false
}
如果要检查特殊字符
function validate(dis)
{
var filter = /^[A-Za-z0-9]+$/;
var ele = dis.getElementsByTagName("input");
for(var i=0;i<ele.length;i++)
{
if(ele[i].getAttribute("type") == "text")
{
if(ele[i].value == "")
{
alert(ele[i].getAttribute('name')+" is required feild");
ele[i].focus();
return false;
}
else if(!filter.test(ele[i].value))
{
alert(ele[i].getAttribute('name')+" requires letters and numbers only");
ele[i].focus();
return false;
}else;
}
// you can check for radio and checkboxes
//eg : if(ele[i].getAttribute("type") == "radio")
// {
// Your code here
// }
}
return true; // to prevent from form submission use false
}