说明:验证是否为空的前提首先要保证是在提交form之前验证的,如果验证结果有为空的项那么限制表单不能提交,并且提示验证错误信息,这部分属于JS部分的东西,与后台业务逻辑层和控制层基本没有任何关系。
限制提交的方法可以是在form标签里限制,也可以是在submit按钮上添加onclick事件限制:
<form action=".." method="post" onsubmit="return check();">
<input type="submit" value="提交" onclick="return check()" >
案例:
<form action="./login.action" method="post" onsubmit="return check();">
<table>
<tr>
<td width="451"> </td>
<td width="378">
<table >
<tr>
<td width="60"> </td>
<td>
<font color="#000000">用户名:</font>
</td>
<td align="left"> <input name="userInfo.userName" id="userName" type="text">
<span id="checkUserName"></span>
</td>
<tr> <td> </td>
<td align="right" nowrap>
<font color="#000000">密 码:</font>
</td>
<td align="left">
<input name="userInfo.password" id="password" type="password">
<span id="checkPassword"></span>
</td>
</tr>
<tr>
<td colspan="4" align="center" nowrap>
<input type="submit" id="btnLog" value=" 登 录 " >
<input type="reset" value=" 重 置 ">
</td>
</tr>
</table>
</form>
<!--引入js文件 jquery-->
<script type="text/javascript" src="js/common/jquery-1.5.1.min.js"></script>
<script type="text/javascript">
function check(){
var userName=$("#userName").val();
var password=$("#password").val();
alert(userName);
alert(password);
if(userName==""){
$("#checkUserName").html("<font color='red'>用户名不能为空!</font>");
return false;
}
if(password==""){
$("#checkPassword").html("<font color='red'>密码不能为空!</font>");
return false;
}
return true;
}
</script>
限制提交的方法可以是在form标签里限制,也可以是在submit按钮上添加onclick事件限制:
<form action=".." method="post" onsubmit="return check();">
<input type="submit" value="提交" onclick="return check()" >
案例:
<form action="./login.action" method="post" onsubmit="return check();">
<table>
<tr>
<td width="451"> </td>
<td width="378">
<table >
<tr>
<td width="60"> </td>
<td>
<font color="#000000">用户名:</font>
</td>
<td align="left"> <input name="userInfo.userName" id="userName" type="text">
<span id="checkUserName"></span>
</td>
<tr> <td> </td>
<td align="right" nowrap>
<font color="#000000">密 码:</font>
</td>
<td align="left">
<input name="userInfo.password" id="password" type="password">
<span id="checkPassword"></span>
</td>
</tr>
<tr>
<td colspan="4" align="center" nowrap>
<input type="submit" id="btnLog" value=" 登 录 " >
<input type="reset" value=" 重 置 ">
</td>
</tr>
</table>
</form>
<!--引入js文件 jquery-->
<script type="text/javascript" src="js/common/jquery-1.5.1.min.js"></script>
<script type="text/javascript">
function check(){
var userName=$("#userName").val();
var password=$("#password").val();
alert(userName);
alert(password);
if(userName==""){
$("#checkUserName").html("<font color='red'>用户名不能为空!</font>");
return false;
}
if(password==""){
$("#checkPassword").html("<font color='red'>密码不能为空!</font>");
return false;
}
return true;
}
</script>

本文介绍如何使用JavaScript进行表单验证,确保提交的数据完整无误。通过具体案例展示了如何阻止空字段提交,并给出提示信息。
284

被折叠的 条评论
为什么被折叠?



