在jq提供的校验规则不能满足要求时,需要自定义校验规则:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>表单校验</title>
<script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
<!--引入校验所需的js包-->
<script src="js/jquery.validate.min.js" type="text/javascript"></script>
<style>
body {
margin-top: 20px;
margin: 0 auto;
}
.carousel-inner .item img {
width: 100%;
height: 300px;
}
font {
color: #3164af;
font-size: 18px;
font-weight: normal;
padding: 0 10px;
}
.error {
color: red
}
</style>
<script type="text/javascript">
//自定义校验规则
$.validator.addMethod(
//规则名称
"checkPhone",
//校验的函数
function(value, element, params) {
//定义一个标志
var flag = false;
//value:输入的内容
//element:被校验的元素对象
//params:规则对应的参数值
//目的:对输入的username进行ajax校验
//返回false代表该校验不通过
var myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0-9]{1})|(15[0-3]{1})|(15[4-9]{1})|(18[0-9]{1})|(199))+\d{8})$/;
if(value != '' && value.length == 11 && myreg.test(value)) {
flag = true;
}
return flag;
}
);
$(function() {
$("#myform").validate({
rules: {
"username": {
"required": true,
"checkPhone": true
}
},
messages: {
"username": {
"required": "手机号不能为空",
"checkPhone": "手机号不正确"
}
}
});
});
</script>
</head>
<body>
<form id="myform" class="form-horizontal" action="${pageContext.request.contextPath }/register" method="post" style="margin-top: 5px;">
<div class="form-group">
<label for="username" class="col-sm-2 control-label">用户名</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="username" name="username" placeholder="请输入用户名">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" width="100" value="注册" name="submit" style="height: 35px; width: 100px;">
</div>
</div>
</form>
</body>
</html>