Giter VIP home page Giter VIP logo

validator.js's Introduction

validator.js

一个简单、轻量级,但功能强大的 Validator 组件,并且可以方便扩展类型判断:

  • jQuery / Zepto 插件,即插即用 (若同时存在 jQuery 和 Zepto,将以插件执行时,优先作用于 jQuery) *
  • 基于 HTML5 的 API 设计
  • 兼容主流浏览器,包括 IE 6+
  • jQuery (1.8.3、1.11.1)、Zepto (1.1.3) tested

DEMO form validator

线上运行版本

使用方法

一、实例化

$('#form_id').validator(options);

validator 方法支持一个 options 对象作为参数。当不传参数时,options 具备默认值。参数储存在 $('').data('__options__')。完整的对象如下描述:

options = {
  // 需要校验的表单项,(默认是 `[required]`),支持任何 jQuery 选择器可以选择的标识
  identifie: {String},

  // 校验不通过时错误时添加的 class 名(默认是 `error`),当校验为空时,还同时拥有 `empty` 这个 classname
  klass: {String},

  // 错误出现时 `klass` 放在当前表单项还是父节点(默认是当前表单项)
  isErrorOnParent: {Boolean},

  // 触发表单项校验的方法,当是 false 在点 submit 按钮之前不校验(默认是 `blur`)
  method: {String | false},

  // 出错时的 callback,第一个参数是所有出错表单项集合
  errorCallback(unvalidFields): {Function},

  before: {Function}, // 表单检验之前
  after: {Function}, // 表单校验之后,只有 __return true__ 才会提交表单
 }

二、验证表单

$('#form_id').validator(); // or
$('#form_id').validator(options);

validator 方式支持一个 options 对象作为参数,该参数只在调用时供__一次性__使用。当不传参数时,options 使用 validator 的参数作为默认值。完整的对象如下描述:

options = {
  // 需要校验的表单项,(默认是 `[required]`),支持任何 jQuery 选择器可以选择的标识
  identifie: {String},

  // 校验不通过时错误时添加的 class 名(默认是 `error`),当校验为空时,还同时拥有 `empty` 这个 classname
  klass: {String},

  // 错误出现时 `klass` 放在当前表单项还是父节点(默认是当前表单项)
  isErrorOnParent: {Boolean},

  // 触发表单项校验的方法,当是 false 在点 submit 按钮之前不校验(默认是 `blur`)
  method: {String | false},

  // 出错时的 callback,第一个参数是所有出错表单项集合
  errorCallback(unvalidFields): {Function},
 }

三、HTML 标记

目前 type 的类型支持 email/tel/url/range/number 等 HTML5 Form API 支持的类型,当 type 不存在,但为验证项时,则测试表单是否有空;当有标记 maxlength/minlength 的时候验证表单值的长度;当有 min/max 的时候和 type=range 一样验证当前值是否在 min/max 区间:min <= value <= max

同时,如果表单存在 pattern 属性,则不使用 type 作为验证,保持与 HTML5 API 一致,可以作为一种表单自定义验证的方式。比如下面这个表项,将不按 type="email" 来验证,而是使用 pattern 中的正则表达式来验证:

<input type="email" pattern="参照 HTML5 规范的正则表达式" />

注:type 的支持在 validator.js 中的 patterns 这个对象中。

1. 一般标记

在 html 标记上,一个需要验证的表单项,需要加上 required 属性,或者 options.identifie 中指定的选择器名。如:

<input type="email" required />
<select required>
  <option>...
</select>
<div contenteditable pattern="^\d+$"></div>

2. Checkbox & Radio

input:checkbox 默认不校验,input:radio 根据 name 属性来区分组别,也即当所有 name='abc' 的 radio 有一个被 checked,那么表示这一组 radio 通过验证:

<label><input type="radio" required name="abc" value="A">[A]</label>
<label><input type="radio" required name="abc" value="B">[B]</label>
<label><input type="radio" required name="abc" value="C">[C]</label>

3. 异步支持

当需要异步验证时,在表单添加一个 data-url 的属性指定异步验证的 URL 那可,有几个可选的项:

data-url: 异步验证的 url
data-method: [可选] AJAX 请求的方法: get,post,getJSON 等,默认是 get
data-key: [可选] 发送当前表单值时用的 key,默认是 'key':$.get(url, {key: 表单的值})

html 标记如下:

<input type="text" data-url="https://api.github.com/legacy/user/search/china" data-method="getJSON" required>

4. 二选一

支持二选一,比如联系方式,座机和手机可以只填一项。HTML 的标记如下,在需要此功能的项添加 data-aorb 属性,指定 a 或者 b,顺序可以相反:

<input data-aorb="a" >
<input data-aorb="b" >

NOTE: 顺便说一句,实现多选一代码可以更简单一点,但问题在于这是个好设计吗?所以多想一下。

5. 支持自定义元素的事件

可以在 html 中添加 data-event 以在单独的元素中触发自定义事件。假设我们设置一个 hello 事件,最终会触发在验证这个表单前触发 before.hello 事件,并且在验证完当前表单后触发一个 after.hello 事件。默认不触发任何事件:

<input id="event" type="text" data-event="hello" required>

可以使用标准的 jQuery on 来监听这个事件:

$('#event').on('before:hello', function(event, element){
  alert('`before.hello` event trigger on $("#' + element.id + '")');
})

$('#event').on('after:hello', function(event, element){
  alert('`after.hello` event trigger on $("#' + element.id + '")');
})

6. 支持在指定元素添加错误 class

可以在 html 中添加 data-parent 用以指定需要添加错误 class 的元素,属性值为任意 jQuery 选择器支持的语法。例如一个表单被嵌套多层,可以通过在该表单上添加 data-parent='div[name="test"].parent' 来制定在距该表单最近的父级元素中 name="test" 并且 class="parent"div 元素上添加错误 class。例:

<div name="test" class="parent">
	<p>
		<input type="test" data-parent="div[name="test"].parent" required>
	</p>
</div>

通用约定和代码规范:

  • 以 2-spaces 作为缩进
  • 变量先定义后赋值(除非赋值可以写成单行)
  • 代码中出现以 $ 开头的对象,该为 jQuery 对象,比如 $item

测试用例:

使用 index.php 这个文件

许可协议

基于 MIT 协议授权,你可以使用于任何地方(包括商业应用)、修改并重新发布。详见:LICENSE

贡献者

validator.js's People

Contributors

chrisyip avatar hax avatar iwillhappy1314 avatar sofish avatar sunaiwen avatar z8 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

validator.js's Issues

在共用放置错误样式的父元素时,`focusin` 会相互影响。

以这个 pull requests 为例 https://github.com/sofish/validator.js/pull/20。

如果把包裹 contenteditablediv 去掉,就会共用 form 作为错误样式放置的对象,这时候从第一个 div 跳到第二个 div 时,formclass 会被移除。

想到方案是在 focusin 时判断一遍父元素里的待校验项是否都正确:

$form.on('focusin', identifie, function(e) {
  var invalid = false;
  if (isErrorOnParent) {
    var errElem = errorElement($(this), ...);
    errElem.find(idnetifie).each(function(){
      invalid = validate.call(this, ...)
    })
  }
  if (!invalid) {
    removeErrorClass.call(this, $(this), 'error unvalid empty', isErrorOnParent);
  }
})

有没有更优雅、高效的方法?

更灵活的 isErrorOnParent

isErrorOnParent: {BOOL} 改成 isErrorOnParent: {SEL} 应该可以有更好的灵活性,举例来说:

<div class="form-item">
  <label>
    <input type="text" required>
  <div class="custom-error-element">

如果使用 isErrorOnParent: 'div.form-item' 的话,就可以更好地处理自定义错误的样式。

如果只是 BOOL,那只能应用在 label(在这个例子里)上,限制比较大。

Getting more done in GitHub with ZenHub

Hola! @angrilove has created a ZenHub account for the sofish organization. ZenHub is the only project management tool integrated natively in GitHub – created specifically for fast-moving, software-driven teams.


How do I use ZenHub?

To get set up with ZenHub, all you have to do is download the browser extension and log in with your GitHub account. Once you do, you’ll get access to ZenHub’s complete feature-set immediately.

What can ZenHub do?

ZenHub adds a series of enhancements directly inside the GitHub UI:

  • Real-time, customizable task boards for GitHub issues;
  • Multi-Repository burndown charts, estimates, and velocity tracking based on GitHub Milestones;
  • Personal to-do lists and task prioritization;
  • Time-saving shortcuts – like a quick repo switcher, a “Move issue” button, and much more.

Add ZenHub to GitHub

Still curious? See more ZenHub features or read user reviews. This issue was written by your friendly ZenHub bot, posted by request from @angrilove.

ZenHub Board

截至目前,DEMO 中的 js 版本还不是最新的~

如题,今天从 demo 中获取了 validator.js 文件,然后自己又新增了 type=text 验证条件中使minlength 生效的方法,而后准备提交的时候发现了代码中已经有了这个验证。
请更新 DEMO 中的 validator.js

patterns:number数字验证有错误

return result && (0 >= step ? (text >= min && text <= max) : 0 === (text + min) % step && (text >= min && text <= max))
以上代码中,如果step大于0,应该是 (text - min) % step === 0 把,不是 text + min

, klass = options.error || 'error'

, klass = options.error || 'error'

源码里这样写,说明配置的时候用klass,没地方统一全局设置放置error class的dom,我也是醉了

say NO to IE 6

i don't think there is any necessary to support IE 6(or evan IE7).

错误class参数错误

// 校验不通过时错误时添加的 class 名(默认是 error),当校验为空时,还同时拥有 empty 这个 >classname
klass: {String},

不是klass 应该是error

表单验证异步请求问题

有这样一个验证码验证需求:

<input type="text" data-url="https://api.github.com/legacy/user/search/china" data-method="get" data-key="code" required>

返回值为josn:

{
      status : 'ok'     //ro  'no'
}

如果status为ok时,想请求一个回调函数。这个操作怎么写?貌似该方法没有回调函数?

Checkbox 的 name 值可能出现像 [] 这样的字符

如果代码写成:identifier = 'input:' + type + '[name="' + this.$item.attr('name') + '"g]'。那么当 name=一般的值加上[] 的时候,选择器变成这样:$('input:checkbox[name=一般的值加上[]]') 会报错。所以最好加上引号:

identifier = 'input:' + type + '[name="' + this.$item.attr('name') + '"g]'

外部触发验证

在某些场景下,需要在外部触发验证,像是这样:$("form").trigger("form:validator")

点击单选按钮会报错

点击radio的时候会报如下错误,在chrome和FF下都有:
Uncaught Error: Syntax error, unrecognized expression: input:radio[name="abc"g] jquery-1.8.3.min.js:2
nt.error jquery-1.8.3.min.js:2
ut jquery-1.8.3.min.js:2
g.querySelectorAll.vt jquery-1.8.3.min.js:2
nt jquery-1.8.3.min.js:2
v.fn.extend.find jquery-1.8.3.min.js:2
v.fn.v.init jquery-1.8.3.min.js:2
v jquery-1.8.3.min.js:2
patterns._checker validator.js:115
patterns.radio validator.js:107
validateReturn validator.js:198
validate validator.js:258
validateFields validator.js:275
v.extend.each jquery-1.8.3.min.js:2
v.fn.v.each jquery-1.8.3.min.js:2
validateFields validator.js:274
v.event.dispatch jquery-1.8.3.min.js:2
v.event.add.o.handle.u

有人能解释一下
identifier = 'input:' + type + '[name="' + this.$item.attr('name') + '"g]'
最后的g是什么意思吗?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.