编写基于Jquery的表单验证插件 完整版html
时间: 2024-02-01 17:03:55 浏览: 72
基于jquery的表单验证代码
<!DOCTYPE html>
<html>
<head>
<title>jQuery表单验证插件</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="jquery.validate.min.js"></script>
<style>
form label.error {
color: red;
font-size: 12px;
font-weight: normal;
padding-left: 5px;
}
</style>
</head>
<body>
<h1>jQuery表单验证插件</h1>
<form id="myForm">
<label for="name">姓名:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">邮箱:</label>
<input type="email" id="email" name="email"><br><br>
<label for="password">密码:</label>
<input type="password" id="password" name="password"><br><br>
<label for="confirm_password">确认密码:</label>
<input type="password" id="confirm_password" name="confirm_password"><br><br>
<label for="phone">电话号码:</label>
<input type="text" id="phone" name="phone"><br><br>
<input type="submit" value="提交">
</form>
<script>
$(document).ready(function() {
$("#myForm").validate({
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 6
},
confirm_password: {
required: true,
minlength: 6,
equalTo: "#password"
},
phone: {
required: true,
phoneCN: true
}
},
messages: {
name: {
required: "请输入姓名",
minlength: "姓名至少为2个字符"
},
email: {
required: "请输入邮箱",
email: "请输入正确的邮箱格式"
},
password: {
required: "请输入密码",
minlength: "密码至少为6个字符"
},
confirm_password: {
required: "请确认密码",
minlength: "密码至少为6个字符",
equalTo: "两次密码输入不一致"
},
phone: {
required: "请输入电话号码",
phoneCN: "请输入正确的中国电话号码格式"
}
}
});
$.validator.addMethod("phoneCN", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length == 11 &&
/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/.test(phone_number);
}, "请输入正确的中国电话号码格式");
});
</script>
</body>
</html>
阅读全文