很多时候,我们都会用到表单,通常表单验证需要前端后端都要设置,以防用户不规则输入,导致系统崩溃,先上代码吧。
<script type="text/javascript">
function check(){
//获取控件内容
var loginname = document.getElementById("inputUsername").value;
var password = document.getElementById("inputPassword").value;
var VerifiCode = document.getElementById("inputVerifiCode").value;
loginname = loginname.replace(/\s*/g,"");// 去除空格 防止用户误点
password = password.replace(/\s*/g,"");
VerifiCode = VerifiCode.replace(/\s*/g,"");
if(loginname == ""){
alert("用户名不能为空");
document.getElementById("inputUsername").focus();//获取焦点
return false;
}
if(password == ""){
alert("密码不能为空");
document.getElementById("inputPassword").focus();
return false;
}
if(VerifiCode == ""){
alert("验证码不能为空");
document.getElementById("inputVerifiCode").focus();
return false;
}
//验证成功
return true;
}
</script>
<form class="form-horizontal" onsubmit="return check()" role="form" action="/Login" name="loginform" method="post">
<div class="form-group">
<label for="inputUsername" class="col-sm-3 control-label">
<span class="glyphicon glyphicon-user"></span>
学号
</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="inputUsername" id="inputUsername" />
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-sm-3 control-label">
<span class="glyphicon glyphicon-asterisk"></span>
密码
</label>
<div class="col-sm-9">
<input type="password" class="form-control" name="inputPassword" id="inputPassword" />
</div>
</div>
<div class="form-group">
<label for="inputVerifiCode" class="col-sm-3 control-label">
<span class="glyphicon glyphicon-asterisk"></span>
验证码
</label>
<div class="col-md-9">
<div class="col-md-7">
<input type="text" class="form-control" id="inputVerifiCode" name="inputVerifiCode" />
</div>
<div class="col-md-2">
<%--下面这块是验证码的--%>
<a href="javascript:getVerifiCode()">
<img id="yzm_img" style="cursor:pointer;width: 100px;height: 36px;margin: 5px 0 0 5px;border-radius: 3px;" title="点击刷新验证码" src="Mcake/getVerifiCode"/>
</a>
<script>
function getVerifiCode() {
$("#yzm_img").prop('src','getVerifiCode?a='+new Date().getTime());
}
</script>
<%--上面这块是验证码的--%>
</div>
<%--<div class="col-md-9">--%>
<%--<input type="button" class="form-control" class="btn btn-block btn-default" value="看不清?刷新" />--%>
<%--</div>--%>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-9">
<div class="col-md-4 col-md-12">
<button type="" class="btn btn-info btn-block" onclick="check()">登录</button>
</div>
<div class="col-md-2"></div>
<div class="col-md-4 col-md-12">
<button type="reset" class="btn btn-danger btn-block">重置</button>
</div>
</div>
</div>
</div>
</form>
这里面头标记form中 οnsubmit="return check()"一定要加上, 因为οnsubmit="return check() 给form加onsubmit 验证所有表单后再提交,可以用返回false 来阻止submit提交
最后感谢各位看官浏览,如果有错,还请说我来,我马上改。