分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

jQuery - Validate

发布时间:2023-09-06 01:50责任编辑:蔡小小关键词:jQuery

jQuery Validate 插件为表单提供了强大的验证功能,让客户端表单验证变得更简单,同时提供了大量的定制选项,满足应用程序各种需求。该插件捆绑了一套有用的验证方法,包括 URL 和电子邮件验证,同时提供了一个用来编写用户自定义方法的 API。

1.14.0 版本下载地址:http://static.runoob.com/download/jquery-validation-1.14.0.zip

导入js库:

<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script><script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>

默认校验规则:

序号规则描述
1required:true必须输入的字段。
2remote:"check.php"使用 ajax 方法调用 check.php 验证输入值。
3email:true必须输入正确格式的电子邮件。
4url:true必须输入正确格式的网址。
5date:true必须输入正确格式的日期。日期校验 ie6 出错,慎用。
6dateISO:true必须输入正确格式的日期(ISO),例如:2009-06-23,1998/01/22。只验证格式,不验证有效性。
7number:true必须输入合法的数字(负数,小数)。
8digits:true必须输入整数。
9creditcard:必须输入合法的信用卡号。
10equalTo:"#field"输入值必须和 #field 相同。
11accept:输入拥有合法后缀名的字符串(上传文件的后缀)。
12maxlength:5输入长度最多是 5 的字符串(汉字算一个字符)。
13minlength:10输入长度最小是 10 的字符串(汉字算一个字符)。
14rangelength:[5,10]输入长度必须介于 5 和 10 之间的字符串(汉字算一个字符)。
15range:[5,10]输入值必须介于 5 和 10 之间。
16max:5输入值不能大于 5。
17min:10输入值不能小于 10。

默认提示:

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.", ???creditcard: "Please enter a valid credit card number.", ???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}." )}

jQuery Validate提供了中文信息提示包,位于下载包的 dist/localization/messages_zh.js,内容如下:

(function( factory ) { ???if ( typeof define === "function" && define.amd ) { ???????define( ["jquery", "../jquery.validate"], factory ); ???} else { ???????factory( jQuery ); ???}}(function( $ ) {/* * Translated default messages for the jQuery validation plugin. * Locale: ZH (Chinese, 中文 (Zhōngwén), 汉语, 漢語) */$.extend($.validator.messages, { ???required: "这是必填字段", ???remote: "请修正此字段", ???email: "请输入有效的电子邮件地址", ???url: "请输入有效的网址", ???date: "请输入有效的日期", ???dateISO: "请输入有效的日期 (YYYY-MM-DD)", ???number: "请输入有效的数字", ???digits: "只能输入数字", ???creditcard: "请输入有效的信用卡号码", ???equalTo: "你的输入不相同", ???extension: "请输入有效的后缀", ???maxlength: $.validator.format("最多可以输入 {0} 个字符"), ???minlength: $.validator.format("最少要输入 {0} 个字符"), ???rangelength: $.validator.format("请输入长度在 {0} 到 {1} 之间的字符串"), ???range: $.validator.format("请输入范围在 {0} 到 {1} 之间的数值"), ???max: $.validator.format("请输入不大于 {0} 的数值"), ???min: $.validator.format("请输入不小于 {0} 的数值")});}));

可以将该本地化信息文件 dist/localization/messages_zh.js 引入到页面:

<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>

使用方式:

1、将校验规则写到控件中

<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script><script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script><script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script><script>$.validator.setDefaults({ ???submitHandler: function() { ?????alert("提交事件!"); ???}});$().ready(function() { ???$("#commentForm").validate();});</script><form class="cmxform" id="commentForm" method="get" action=""> ?<fieldset> ???<legend>输入您的名字,邮箱,URL,备注。</legend> ???<p> ?????<label for="cname">Name (必需, 最小两个字母)</label> ?????<input id="cname" name="name" minlength="2" type="text" required> ???</p> ???<p> ?????<label for="cemail">E-Mail (必需)</label> ?????<input id="cemail" type="email" name="email" required> ???</p> ???<p> ?????<label for="curl">URL (可选)</label> ?????<input id="curl" type="url" name="url"> ???</p> ???<p> ?????<label for="ccomment">备注 (必需)</label> ?????<textarea id="ccomment" name="comment" required></textarea> ???</p> ???<p> ?????<input class="submit" type="submit" value="Submit"> ???</p> ?</fieldset></form>

2、将校验规则写到 js 代码中

$().ready(function() {// 在键盘按下并释放及提交后验证提交表单 ?$("#signupForm").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: "用户名必需由两个字母组成" ?????}, ?????password: { ???????required: "请输入密码", ???????minlength: "密码长度不能小于 5 个字母" ?????}, ?????confirm_password: { ???????required: "请输入密码", ???????minlength: "密码长度不能小于 5 个字母", ???????equalTo: "两次密码输入不一致" ?????}, ?????email: "请输入一个正确的邮箱", ?????agree: "请接受我们的声明", ?????topic: "请选择两个主题" ????} ???})});

messages 处,如果某个控件没有 message,将调用默认的信息

required: true 值是必须的。
required: "#aa:checked" 表达式的值为真,则需要验证。
required: function(){} 返回为真,表示需要验证。

后边两种常用于,表单中需要同时填或不填的元素。

异步验证

remote:URL。使用 ajax 方式进行验证,默认会提交当前验证的值到远程地址,如果需要提交其他的值,可以使用 data 选项。远程地址只能输出 "true" 或 "false",不能有其他输出。

remote: { ???url: "check-email.php", ????//后台处理程序 ???type: "post", ??????????????//数据发送方式 ???dataType: "json", ??????????//接受数据格式 ??????data: { ????????????????????//要传递的数据 ???????username: function() { ???????????return $("#username").val(); ???????} ???}}

添加自定义校验

addMethod:name, method, message
自定义验证方法
// 中文字两个字节jQuery.validator.addMethod("byteRangeLength", function(value, element, param) { ???var length = value.length; ???for(var i = 0; i < value.length; i++){ ???????if(value.charCodeAt(i) > 127){ ???????????length++; ???????} ???} ?return this.optional(element) || ( length >= param[0] && length <= param[1] ); ??}, $.validator.format("请确保输入的值在{0}-{1}个字节之间(一个中文字算2个字节)"));// 邮政编码验证 ??jQuery.validator.addMethod("isZipCode", function(value, element) { ??????var tel = /^[0-9]{6}$/; ???return this.optional(element) || (tel.test(value));}, "请正确填写您的邮政编码");

注意:要在 additional-methods.js 文件中添加或者在 jquery.validate.js 文件中添加。建议一般写在 additional-methods.js 文件中。

注意:在 messages_cn.js 文件中添加:isZipCode: "只能包括中文字、英文字母、数字和下划线"。调用前要添加对 additional-methods.js 文件的引用。

radio 和 checkbox、select 的验证

radio 的 required 表示必须选中一个。

<input ?type="radio" id="gender_male" value="m" name="gender" required /><input ?type="radio" id="gender_female" value="f" name="gender"/>

checkbox 的 required 表示必须选中。

<input type="checkbox" class="checkbox" id="agree" name="agree" required />

checkbox 的 minlength 表示必须选中的最小个数,maxlength 表示最大的选中个数,rangelength:[2,3] 表示选中个数区间。

<input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" required minlength="2" /><input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]" /><input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]" />

select 的 required 表示选中的 value 不能为空。

<select id="jungle" name="jungle" title="Please select something!" required> ???<option value=""></option> ???<option value="1">Buga</option> ???<option value="2">Baga</option> ???<option value="3">Oi</option></select>

select 的 minlength 表示选中的最小个数(可多选的 select),maxlength 表示最大的选中个数,rangelength:[2,3] 表示选中个数区间。

<select id="fruit" name="fruit" title="Please select at least two fruits" class="{required:true, minlength:2}" multiple="multiple"> ???<option value="b">Banana</option> ???<option value="a">Apple</option> ???<option value="p">Peach</option> ???<option value="t">Turtle</option></select>

 例:

 ?<script type="text/javascript"> ?$(function(){ ?????loadSelect(‘parentId‘,null,true,‘--暂不设置--‘,null,‘getDeptSelect‘,null);//部门选择 ???????var validator =$(‘#form1‘).validate({ ?????????????errorElement: ‘p‘, ???????????errorClass: ‘help_block‘, ???????????focusInvalid: true, ???????????debug : true, ???????????rules: { ???????????????organizationCode: {required: true}, ???????????????name: { ???????????????????required: true, ???????????????????remote : { ???????????????????????url: "checkDeptName", ??????????//后台处理程序 ???????????????????????type: "post", ??????????????//数据发送方式 ???????????????????????dataType: "json", ??????????//接受数据格式 ???????????????????????data: { ????????????????????//要传递的数据 ???????????????????????????????organizationCode: function() { ???????????????????????????????????return $("#organizationCode").val(); ???????????????????????????????}, ???????????????????????????????name: function() { ???????????????????????????????????return $("#name").val(); ???????????????????????????????} ???????????????????????????} ???????????????????????} ???????????????????????????????????????}, ???????????????parentId: {required: false}, ???????????????description: {required: false}, ???????????????sort:{required: true,number:true} ????????????}, ???????????messages: { ???????????????organizationCode: {required: "请输入单位"}, ???????????????name : {required: "请输入部门名称",remote:"该单位下已存在该部门名称"}, ???????????????parentId : {required: false}, ???????????????description : {required: false}, ???????????????sort:{required:"请输入数字",number:"请输入数字"} ???????????}, ???????????????highlight: function (e) { ???????????????$(e).closest(‘.form-group‘).removeClass(‘has-info‘).addClass(‘has-error‘); ???????????}, ???????????success: function (e) { ???????????????$(e).closest(‘.form-group‘).removeClass(‘has-error‘);//.addClass(‘has-info‘); ???????????????$(e).remove(); ???????????}, ???????????errorPlacement: function (error, element) { ???????????????if(element.is(‘input[type=checkbox]‘) || element.is(‘input[type=radio]‘)) { ???????????????????var controls = element.closest(‘div[class*="col-"]‘); ???????????????????if(controls.find(‘:checkbox,:radio‘).length > 1) controls.append(error); ???????????????????else error.insertAfter(element.nextAll(‘.lbl:eq(0)‘).eq(0)); ???????????????} ???????????????else if(element.is(‘.select2‘)) { ???????????????????error.insertAfter(element.siblings(‘[class*="select2-container"]:eq(0)‘)); ???????????????} ???????????????else if(element.is(‘.chosen-select‘)) { ???????????????????error.insertAfter(element.siblings(‘[class*="chosen-container"]:eq(0)‘)); ???????????????} ???????????????else error.insertAfter(element.parent()); ???????????}, ????????????submitHandler:function(form){ ????????????????$.ajax({ ???????????????????url: "${ctx}/organization/department/addDept?t=" + Math.random(), ???????????????????method: "post", ???????????????????data : $(‘#form1‘).serialize(), ???????????????????dataType: "json", ???????????????????beforeSend : function(){ ???????????????????????$("#btn_add").attr("disabled", true); ???????????????????}, ???????????????????success : function(data){ ???????????????????????if(data.code == 1){ ????????????????????????????????????????????????????????window.parent.window.document.getElementById("main-frame").contentWindow.fnSearch(); ????????????????????????????parent.window.closeWind("conferenceDepartment_add"); ???????????????????????????????????????????????????}else{ ???????????????????????????$("#btn_add").removeAttr("disabled"); ???????????????????????????parent.$.messager.alert(‘消息提示‘, data.msg, ‘info‘); ???????????????????????} ???????????????????} ???????????????}); ????????????} ????????}); ?????}) ?</script>

参考链接:http://www.runoob.com/jquery/jquery-plugin-validate.html

jQuery - Validate

原文地址:https://www.cnblogs.com/lijianda/p/8934361.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved