我们平时在上网的时候,难免会进行用户的注册登录操作,这时候就会出现表单的验证,如用户名长度要求,密码复杂度要求等等。本次我将介绍使用jQuery插件jquery.validate.js进行简单的表单验证,当然实际开发过程中的表单验证过程远比这个复杂,其中还涉及AJAX等技术,这里只是简单的使用。
一、首先在script标签中引入jQuery库,写一个简单的form表单
<form action="#" method="post">
<p>用户名(长度在5-10位):<input name="username" type="text"></p>
<p>密码(长度不小于位):<input name="password1" type="password"></p>
<p>确认密码(和密码保持一致):<input name="password2" type="password"></p>
</form>
<script type="text/javascript" src="js/jquery-1.12.3.js"></script> <script type="text/javascript" src="js/jquery.validate.js"></script>
二、在表单的input标签中添加验证的属性
为了使表单验证信息提示显示醒目,可以先在style标签中加上一个样式
在input标签中加入需要验证的属性:
<form id="myForm" action="xxx"> <p>用户名(长度在5-10位):<input name="username" type="text" required rangelenth></p> <p>密码(长度不小于6位):<input id="pwd" name="password1" type="password" required minlength="6"></p> <p>确认密码(和密码保持一致):<input name="password2" type="password" equalTo="#pwd"></p> <p><input class="submit" type="submit" value="提交"></p> </form>
在messages中定义该规则对应的错误提示信息:
默认错误提示信息如下:
required: "This field is required.", remote: "Please fix this field.", email: "Please enter a valid email address.", url: "Please enter a valid URL.", date: "Please enter a valid date.", dateISO: "Please enter a valid date ( ISO ).", number: "Please enter a valid number.", digits: "Please enter only digits.", equalTo: "Please enter the same value again.", maxlength: $.validator.format( "Please enter no more than {0} characters." ), minlength: $.validator.format( "Please enter at least {0} characters." ), rangelength: $.validator.format( "Please enter a value between {0} and {1} characters long." ), range: $.validator.format( "Please enter a value between {0} and {1}." ), max: $.validator.format( "Please enter a value less than or equal to {0}." ), min: $.validator.format( "Please enter a value greater than or equal to {0}." ), step: $.validator.format( "Please enter a multiple of {0}." )
自定义错误规则和错误提示信息:
注:设置错误规则可以在页面中直接设置,也可在js代码中rules中设置,建议在rules就定义好
<script type="text/javascript">
$(function (){
$("#myForm").validate({
rules:{
username: {
rangelength: [5,10] //使用数组,用户名长度介于5到10之间
}
},
messages:{
username:{
required : "用户名是必填的!",
rangelength : "用户名长度在5-10位",
},
password1:{
required: "密码是必填的!",
minlength:"密码长度不能小于6位"
},
password2:{
equalTo:"两次输入密码必须相同"
}
}
})
})
</script>
使用浏览器打开即可看到:
当然更多复杂使的用方法可以去官网学习:https://jqueryvalidation.org/