15 Star 41 Fork 10

qdbp / zhh.validate.js

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

zhh.validate.js ZHH表单校验插件



这是一个WEB前端校验插件,提供表单字段的配置式校验功能。

使用方便,所有校验参数都提供data-API,常用的校验功能不需要写一行JavaScript代码,即可完全通过配置来实现。

扩展简单,支持开发人员自定义复杂的校验,支持全局预置和页面定制。对基础校验功能也都提供了修改的方法。

整个表单的校验和每个字段行的校验都支持自动触发和手工触发。


说明文档 https://qdbp.gitee.io/project/web/zhh.validate.js/doc/index.html

完整示例 https://qdbp.gitee.io/project/web/zhh.validate.js/doc/register.html


创建本项目的原因


目前校验框架很多,都有各自的优缺点,但实际使用时各种不爽。
因此创建本项目,目标:校验规则支持data-API,配置简洁直观,支持分组校验合并提示,自定义规则扩展简单

与其他校验框架的对比:

https://jqueryvalidation.org/

data-fv-less-than___max="2000" 规则配置复杂
data-fv-different___compare="xxx" 仅支持与固定值对比,不支持与另一控件值对比,没有应用意义

https://formvalidation.io/

只有required, type=number/email/url 等几个HTML5的规则支持配置,其他的规则全都需要写一大堆JavaScript

http://validform.rjboy.cn/

datatype="n0-2000" errormsg="请输入2000以下的数字"
规则不直观,预定义规则较少,规则配置没有以data-开头不符合HTML5标准

https://gitee.com/qdbp/zhh.validate.js (本项目)

data-vld="[ {required:true}, {number:[0,2000]}, {compare:'input[name=fieldName]'} ]"
支持data-API,配置简洁直观,预定义规则丰富

基本概念


校验单元

<form>为基础,其中的每一个class="vld-line"class="form-group"为一个校验单元。

一般就是表单的一个字段。如用户名/密码/注册邮箱等,都可以作为一个校验单元。

校验规则

校验规则,以data-vld="..."的形式配置在输入框上。

<input data-vld="{ label:'登录账号', rules:[ {required:true}, {length:[4,10]}, ... ] }" />

如果label可以自动获取,则简写为:

<input data-vld="[ {required:true}, {length:[4,10]}, ... ]" />

如果只有一个规则,还可以简写为:

<input data-vld="required:true" /> // 必填
<input data-vld="regexp:'mobile'" /> // 手机号码

默认支持的类型有必填校验、长度校验、正则表达式校验、对比校验、AJAX校验、密码强度校验等。

标签文本

错误提示中的占位符{label}表示校验单元里面的标签文本。

标签文本可以自动查找校验单元中的class="vld-label"class="control-label"。会清除前面的星号和后面的冒号。

以下示例,{label}=登录账号:

<label class="vld-label">登录账号</label><input type="text" data-vld="[...]" />

也可以通过配置指定,data-vld="{ label:'登录账号', rules:[...] }"。配置指定优先级高于自动查找。

<label class="vld-label">账号</label><input type="text" data-vld="{ label:'登录账号', rules:[...] }" />

校验示例


<form class="vld-form form-horizontal">
  <div class="control-group vld-line">
    <label class="control-label"><span class="asterisk">*</span> 登录账号</label>
    <div class="controls">
      <input class="span3" type="text" name="account"
        data-vld="[ {required:true}, {length:[4,10]}, {regexp:'ascii'}, {regexp:'illegal-char'}, {ajax:'demo/ajax.txt',options:{type:'GET',dataType:'text'},text:'用户名已被使用'} ]" />
      <span class="help-inline">
        <i class="vld-tips">4-10位数字或字母</i>
      </span>
    </div>
    <div class="controls">
      <p>必填,4-10位,不支持中文字符</p>
      <p>不允许包含!@#$%^*,./\等特殊字符,AJAX校验</p>
    </div>
  </div>
  <div class="control-group vld-line">
    <label class="control-label"><span class="asterisk">*</span> 密码</label>
    <div class="controls">
      <input class="span3" type="password" name="pwd" data-trim="false" 
        data-vld="[ {required:true}, {length:[6,16]}, {regexp:'ascii'}, {compare:'[name=account]',reverse:true}, {pwdlevel:'medium'} ]" />
      <span class="help-inline">
        <i class="vld-tips">密码必须包含字母/数字/特殊字符的任意两种</i>
      </span>
    </div>
    <div class="controls">
      <p>必填,6-16位,支持空格,不支持中文字符,不能与用户名相同</p>
    </div>
  </div>
  <div class="control-group">
    <label class="control-label"> </label>
    <div class="controls">
      <input type="button" class="btn btn-primary input-medium vld-submit" value="提交" />
    </div>
  </div>
</form>

必填校验


{ required:true }

可以自定义提示信息,如:

{ required:true, text:'请同意服务协议' }
{ required:true, text:'请选择{label}' }

如果目标输入框内容为空,则校验不通过。

单选框/复选框,没有选中则校验不通过。

单选框/复选框的校验规则应配置在第一个input上。


字符长度校验


如果目标输入框的字符长度不符合要求,则校验不通过。

min指定字符长度的最小值,max指定最大值,这两个参数至少要指定一个。

如果不是必填项,即使指定了最小长度而输入框为空,也认为校验通过,可以提交。

{ length:{min:4,max:12} } // 字符长度4-12位
{ length:[4,12] } // 字符长度4-12位
{ length:{min:4} } // 字符长度不得小于4位
{ length:[4] } // 字符长度不得小于4位
{ length:{max:12} } // 字符长度不得大于12位

数字校验


如果目标输入框的内容不是数字,或者数字超过了指定范围,则校验不通过。

min指定数字的最小值,max指定最大值,这两个参数可以都不指定。

sign指定是否允许前面的+-号,默认为不允许。

decimal指定小数位数,默认为0,即只允许输入整数。

{ number:true } // 必须是数字
{ number:{min:1900,max:2999} } // 数字必须在1900-2999之间
{ number:[1900,2999] } // 数字必须在1900-2999之间
{ number:{min:1900} } // 数字不得小于1900
{ number:[1900] } // 数字不得小于1900
{ number:{max:2999} } // 数字不得大于2999
{ number:true, sign:true } // 允许+-号
{ number:true, decimal:4 } // 最多4位小数
{ number:true, sign:true, decimal:4 } // 允许+-号, 最多4位小数

正则表达式校验


预定义正则表达式

{ regexp:'xxx' }

xxx指向预定义的正则表达式,url、email、mobile(手机号码)、ascii(只支持英文字符)、illegal-char(不支持非法字符)。

预定义的正则表达式可以自己扩充。

(function(zv) {
 
	// 定义只允许输入数字和字母的表达式
	zv.regexp["number-ascii"] = /^[0-9a-zA-Z]*$/;
	zv.locals["zh-CN"]["regexp-number-ascii"] = "{label}只允许输入数字和字母";
 
	// 定义不允许特殊字符的表达式
	// reverse=true表示反转判断结果, 如果匹配就提示错误
	zv.regexp["illegal-char"] = { value:/[!@#$%^\*,.\-<>]/, reverse:true };
	zv.locals["zh-CN"]["regexp-illegal-char"] = "{label}不支持!@#$%^*,.-<>等特殊字符";
 
})(jQuery.fn.zhhvalidate.defaults);

reverse:true表示反转判断结果,如果匹配就提示错误。

illegal-char这个例子里,意味着只要出现这些特殊字符就会提示错误。

指定正则表达式

{ regexp:/^[0-9a-zA-Z]*$/, text:'{label}只允许输入数字和字母' }

指定正则表达式时text错误提示不能省略!

正则表达式校验,表示该字段必须匹配正则,匹配为通过,不匹配则提示错误。

data-ignore-case="true"表示忽略大小写,默认为区分大小写。

data-reverse="true"表示反转判断结果,如果匹配就提示错误。


相等校验


{ compare:'selector' }
{ compare:'selector', reverse:true }

相等校验,表示该字段与另一字段必须相等,相等为通过,不相等则提示错误。

selector,通过jQuery选择符来从

中查找元素作为对比目标。

例如:确认密码必须与登录密码相同。{ compare:'input[name=pwd]' }指向登录密码输入框。

reverse:true表示反转判断结果,如果相等就提示错误。

例如:密码不能与用户名相同: { compare:'input[name=account]', reverse:true }


服务端校验


{ ajax:'url.do' }
{ ajax:'url.do', fields:fields }
{ ajax:'url.do', fields:fields, options:{ type:GET|POST, dataType:json|html|text, ...} }

如果服务端返回字符串,true1表示校验通过;false0表示校验不通过;其他字符串表示校验不通过,这个字符串就是错误提示。

如果服务端返回JSON格式的数据,就需要自已定义AJAX解析函数了:

(function(zv) {
    // 自定义AJAX解析函数
    var parse = zv.ajax.parse;
    zv.ajax.parse = function(e, json) {
        if ($.isPlainObject(json)) {
            return { passed:json.code=="000000", text:json.message };
        } else { // 调用原解析函数
            return parse.call(this, e, json);
        }
    };
})(jQuery.fn.zhhvalidate.defaults);

data-vld选项


<form data-vld="init:true,oninput:true,focus:true,failFast:false,tips:true,disabled:false">
<div class="vld-line" data-vld="group:true,failFast:false,tips:true,disabled:false"></div>
<input data-vld="tips:true,disabled:false"></input>

init:true|false是否需要初始化事件绑定,默认为true。如果不初始化, 则只有在点提交按钮时才会触发表单校验;如果初始化,则在校验目标输入框内容改变时、失去焦点时、选择框点击时均会触发单元校验,而且在点击

中的class="vld-submit"按钮时会校验整个表单,如果所有校验单元全部通过,则自动提交表单。

oninput:true|false是否需要绑定<input><textarea>oninput事件(IE:onpropertychange),默认为true。如果不初始化, 则只有在点提交按钮时才会触发表单校验;如果绑定,则每输入一个字符都会触发单元校验。只在init=true时有效。

focus:true|false是否需要在表单校验失败时将焦点移至第一个失败的校验目标上,默认为true。

failFast:true|false快速失败,默认为false。设置为true时,遇到第一个错误就结束校验;false则即使失败仍然继续执行下一个单元校验。

tips:true|false|fix是否显示错误提示,默认为true。true=显示错误提示,查找校验单元中的vld-tips设置text;false=不自动显示错误提示,一般是js调用时传入false用于自已处理错误提示;fix=绝对定位,自动生成错误,显示在目标输入框的右侧。

disabled:true|false是否禁用校验,默认为false。禁用之后则校验始终为通过。如果上层已经禁用,则该选项无效。如form上配置disabled:true,则input上配置disabled:false仍然不会启用校验;而form上配置disabled:false,input上配置disabled:true可以禁用掉input上的校验。

group:true组合校验,配置在form或vld-line上,将其中包含的所有校验目标作为一组处理,错误提示只有一处。可以结合failFast一起使用,如果failFast!=true,则将所有的错误提示合并在一起显示。


组合校验


group:true组合校验,配置在form或vld-line上,将其中包含的所有校验目标作为一组处理,错误提示只有一处。可以结合failFast一起使用,如果failFast!=true,则将所有的错误提示合并在一起显示。

示例1

<div class="vld-line" data-vld="group:true"></div>

example

示例2

<form data-vld="group:true,failFast:true"></form>

example

方法

clear:清除之前的校验缓存和校验提示

$form.zhhvalidate("clear"); // 清除整个form
$form.find("input[name=account]").zhhvalidate("clear"); // 清除指定校验单元

disable:禁用校验

禁用的含义就是不执行此校验单元,即调用校验方法时此校验单元的结果是通过。 如果form是禁用的,则整个form下的所有校验单元都是禁用的。

$form.zhhvalidate("disable"); // 禁用整个form
$form.find("input[name=account]").zhhvalidate("disable"); // 禁用指定校验单元

enable:启用校验

zhhvalidate("enable", [enableChildren:boolean]): enableChildren=true时循环启用所有校验单元,disable方法没有此参数

$form.zhhvalidate("enable"); // 启用form
$form.zhhvalidate("enable", true); // 启用整个form及所有校验单元
$form.find("input[name=account]").zhhvalidate("enable"); // 启用指定校验单元

如果form是禁用的,则整个form下的所有校验单元都是禁用的:

<form class="form-horizontal" data-options="disabled:true">
  <div class="control-group">
    <label class="control-label">手机号码</label>
    <input name="account" data-vld="disabled:false, rules:[ ... ]" />
  </div>
  <div class="control-group">
    <label class="control-label">短信验证码</label>
    <input name="validCode" data-vld="disabled:false, rules:[ ... ]" />
  </div>
  <div class="control-group">
    <label class="control-label">登录密码</label>
    <input name="newPassword" data-vld="disabled:true, rules:[ ... ]" />
  </div>
</form>

如下结构将只会校验: account validCode; newPassword由于已被禁用将不会校验。

<form class="form-horizontal" data-options="disabled:false">
  <div class="control-group">
    <label class="control-label">手机号码</label>
    <input name="account" data-vld="disabled:false, rules:[ ... ]" />
  </div>
  <div class="control-group">
    <label class="control-label">短信验证码</label>
    <input name="validCode" data-vld="disabled:false, rules:[ ... ]" />
  </div>
  <div class="control-group">
    <label class="control-label">登录密码</label>
    <input name="newPassword" data-vld="disabled:true, rules:[ ... ]" />
  </div>
</form>

其他


全局配置:

$.fn.zhhvalidate.defaults的所有内容都可以自行配置,常用的配置如下:

+function(zv) {
    // 自定义AJAX解析函数
    zv.ajax.parse = function(e, json) {
        return { passed:json.code == "000000", text:json.message };
    };

    // 样式配置
    zv.classes = {
        "line-error": "vld-error", // 校验不通过时, 添加在校验单元上的样式
        "line-passed": null, // 校验通过时, 添加在校验单元上的样式
        "tips-error": "vld-error", // 校验不通过时, 添加在提示信息上的样式
        "tips-passed": "vld-passed", // 校验通过时, 添加在提示信息上的样式
        "tips-loading": "vld-loading" // 正在校验时, 添加在提示信息上的样式, 一般是AJAX校验用到
    };
    // 例如希望校验不通过时在校验单元上添加has-error样式:
    zv.classes["line-error"] = "has-error";

    // 选择符配置
    zv.selectors = {
        target: ["input[data-vld], textarea[data-vld], select[data-vld]"],
        line: [".vld-line", ".form-group"], // form-group是bootstrap的表单行
        label: [".vld-label", ".control-label"], // control-label是bootstrap的标签
        tips: [".vld-tips"]
    };
    // 例如某项目选择了mui前端框架, 校验行是mui-input-row, 那么可以将该样式添加到列表中:
    zv.selectors.line.push(".mui-input-row");

    // 事件绑定
    // 例如希望在文本框获得焦点时在校验单元上添加vld-typing样式:
    zv.bind.push({on:"focus", selector:"input, textarea, select", fn:function() {
        $(this).closest(zv.selectors.line.join(",")).addClass("vld-typing");
    }});
    zv.bind.push({on:"blur", selector:"input, textarea, select", fn:function() {
        $(this).closest(zv.selectors.line.join(",")).removeClass("vld-typing");
    }});
}(jQuery.fn.zhhvalidate.defaults);

提交表单:

$("button[name=dosubmit]").click(function(e) {
    e.preventDefault();
    var $form = $(this).closest("form");
    $form.zhhvalidate(function(e) {
        if (e.passed) {
            $form.submit();
        }
    });
});

手动触发校验:

form.find("input[name=account]").zhhvalidate(function(e) {
    if (e.passed) {
        // do something
    }
});

自己处理错误提示:

$("button[name=dosubmit]").click(function(e) {
    e.preventDefault();
    var $form = $(this).closest("form");
    // 设置tips=false, 不显示错误提示; 还可以设置failFast=true, 每次只显示一条提示
    $form.zhhvalidate({ tips:false }, function(e) {
        // 回调参数e
        // -- passed(boolean) FORM表单校验是否通过
        // -- text(String)    校验不通过时的错误原因(校验通过时为空)
        // -- list([json])    每一个表单行的校验校验结果, json内容见vldinput的回调参数说明
        if (e.passed) {
            $form.submit();
        } else {
            alert(e.text); // 自己处理错误提示
        }
    });
});

自定义校验规则


以下是自定义一个不能小于当前年份的规则

+function(zv) {
    // 不能小于当前年份的自定义规则
    zv.rules.put("year-less-current", function(e) {
        if (parseInt(e.value || 0) < new Date().getFullYear()) {
            return false; // 校验未通过
        }
        return true; // 校验通过
    });
    zv.locals["zh-CN"]["year-less-current"] = "{label}不能小于今年";
}(jQuery.fn.zhhvalidate.defaults);
<input data-vld="[ {number:{max:9999}}, {'year-less-current':true} ]" />

再来一个复杂的自定义规则

// 校验不通过时, 返回值有如下5种情况, 用于获取提示信息以及替换占位符:
// 1. result = false                               -- 根据规则名称从locals获取提示消息
// 2. result = "key"                               -- 根据规则名称-key从locals获取提示消息
// 3. result = { "{text}":text }                   -- text就是提示消息
// 4. result = { "key":value }                     -- 根据规则名称-key从locals获取提示消息, 并替换占位符{key}
// 5. result = { "{key}":key, x:xvalue, y:yvalue } -- 根据规则名称-key从locals获取提示消息, 并替换占位符{x},{y}
+function(zv) {
    // 年份自定义规则的提示消息
    zv.locals["zh-CN"]["year-format"] = "{label}格式错误";
    zv.locals["zh-CN"]["year-format-less-current"] = "{label}不能大于今年";
    zv.locals["zh-CN"]["year-format-max"] = "{label}不能大于{max}";
    zv.locals["zh-CN"]["year-format-range"] = "{label}必须在{min}~{max}之间";
    // 年份自定义规则的伪代码
    // { 'year-format':true }
    // { 'year-format':true, max:9999 }
    // { 'year-format':true, min:2050, max:9999 }
    zv.rules.put("year-format", function(e) {
        var value = parseInt(e.value);
        if ('格式错误') {
            return false; // 第1种情况, 规则名称, "year-format" = "{label}格式错误"
        } else if (value < '今年') {
            return "less-current"; // 2: 规则名称-key, "year-format-less-current" = "{label}不能小于今年"
        } else if ('某某特定条件') {
            return { "{text}":"某某特定错误提示" }; // 3: 直接返回错误提示文本
        } else if (e.rule.max != null && value > e.rule.max) {
            // { 'year-format':true, max:9999 }
            // 4: "year-format-max" = "{label}不能大于{max}"
            return { "max":e.rule.max };
        } else if (e.rule.min != null && e.rule.max != null && (value < e.rule.min || value > e.rule.max)) {
            // { 'year-format':true, min:2050, max:9999 }
            // 5: "year-format-range" = "{label}必须在{min}~{max}之间"
            return { "{key}":"range", "min":e.rule.min, "max":e.rule.max };
        }
        return true; // 校验通过
    });
}(jQuery.fn.zhhvalidate.defaults);
The MIT License (MIT) Copyright (c) 2018 qdbp Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

ZHH表单校验插件,是一个WEB前端校验插件,提供表单字段的配置式校验功能。 展开 收起
JavaScript 等 2 种语言
MIT
取消

发行版 (2)

全部

贡献者

全部

近期动态

加载更多
不能加载更多了
JavaScript
1
https://gitee.com/qdbp/zhh.validate.js.git
git@gitee.com:qdbp/zhh.validate.js.git
qdbp
zhh.validate.js
zhh.validate.js
master

搜索帮助