jQuery的表单验证插件:validate详解与使用示例
$(document).ready(function() {
$("#myform").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required"
},
messages: {
firstname: "请输入您的名字",
lastname: "请输入您的姓氏",
username: {
required: "请输入用户名",
minlength: "用户名至少需要 2 个字符"
},
password: {
required: "请输入密码",
minlength: "密码至少需要 5 个字符"
},
confirm_password: {
required: "请输入确认密码",
minlength: "确认密码至少需要 5 个字符",
equalTo: "两次输入密码不一致"
},
email: "请输入一个有效的电子邮件地址",
topic: "请选择至少两个兴趣主题",
agree: "请接受使用条款。"
},
errorElement: "em",
errorPlacement: function(error, element) {
// 错误信息放置在输入框的后面
error.insertAfter(element);
},
highlight: function(element, errorClass, validClass) {
$(element).addClass(errorClass).removeClass(validClass);
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass(errorClass).addClass(validClass);
}
});
});
这段代码使用jQuery Validate插件来验证一个表单的输入数据是否满足预设的规则。它定义了一些基本的验证规则和错误信息,并指定了错误提示的显示方式。在实际应用中,开发者可以根据具体需求调整规则和错误消息。
评论已关闭