jQuery插件validation
表单校验插件:
在学习javascript时候,我们⼿动的完成过表单数据的校验,这项功能在实际开发中也是常⻅的,属于通⽤功能,
但是单纯的通过javascript进⾏校验,如果选项过多,那么还是有些⼒不从⼼。实际在开发中我们都是使⽤第三⽅⼯具,本案例中我们将使⽤jQuery插件validation进⾏表单的校验。
validation插件的使⽤步骤:
1、下载validation⼯具。
下载地址:https://github.com/jquery-validation/jquery
validation/releases/download/1.17.0/jquery-validation-1.17.0.zip
2、导⼊⼯具jquery-3.4.1.js、jquery.validate.js、messages_zh.js。
3、编写form表单信息并在脚本中给form表单绑定validate验证⽅法。
4、在form表单元素中逐个指定校验规则。
5、实现注册表单校验案例
jquery插件⽹址:www.jq22.com
前端学习⽹站:www.w3school.com.cn www.runoob.com
5.1、日期插件
引入My97DatePicker
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="My97DatePicker/My97DatePicker/WdatePicker.js"></script>
</head>
<body>
<form action="" method="post">
出生日期:<input class="Wdate" type="text" onclick="WdatePicker({el:this,dateFmt:'yyyy-MM-dd HH:mm:ss'})">
</form>
</body>
</html>
5.1、表单校验
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jq表单插件</title>
<!-- 1. 引入jq函数库 -->
<script src="./"></script>
<!-- 2. jq的validate插件库 -->
<script src="./js/jquery.validate.js"></script>
<!-- 3. 提示信息文件 -->
<script src="./js/messages_zh.js"></script>
<style>
em.error{
color: red;
font-size: 12px;
}
</style>
<script>
$(function(){
// 1. 调用校验函数
$("#formId").validate({
rules: { // 指定校验规则
"username": {
required: true, // 必填项
rangelength: [5, 12]
},
"pwd": {
required: true,
digits: true
},
"repwd": {
equalTo: "#pwd"
},
"email": {
email: true
},
"birthday": {
dateISO: true
}
},
messages: { // 错误提示信息
"username": {
required: "这个是你必填的内容!",
rangelength: "长度必须为5~12个字符"
},
"pwd": {
required: "密码必填!",
digits: "必须是数字!"
},
"repwd": {
equalTo: "确认密码与密码不一致!"
},
"email": {
email: "邮箱不合法!"
},
"birthday": {
dateISO: "日期不合法!"
}
},
errorElement: "em" // 指定错误提示样式
});
})
</script>
</head>
<body>
<form id="formId" method="post" action="#">
<table border="1" cellspacing="0" width="400" align="center">
<tr align="center">
<td colspan="2">⽤户注册</td>
</tr>
<tr>
<td align="right">⽤户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td align="right">密码:</td>
<td><input id="pwd" type="password" name="pwd"></td>
</tr>
<tr>
<td align="right">确认密码:</td>
<td><input type="password" name="repwd"></td>
</tr>
<tr>
<td align="right">Email:</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td align="right">出⽣⽇期:</td>
<td><input type="text" name="birthday"></td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" value="注册"></td>
</tr>
</table>
</form>
</body>
</html>