Skip to content

yesixuan/common-validate

Repository files navigation

license Build Status Coveralls npm NPM downloads Percentage of issues still open

JS 通用的响应式校验工具。适用 nodejs、vue、react、小程序、原生。数据变化自动触发校验

Usage

import Validator from '@ignorance/validator'

// 待校验数据
const formData = {
  name: 'lisa',
  age: '12'
}

// 校验规则 (默认支持 required min max) 同样支持正则表达式校验、检验函数(必须返回 true|false)
const ruleConfig = {
  name: [
    {
      validator: 'required',
      msg: '必填'
    },
    {
      validator: 'min:2 max:6',
      msg: '长度在 2 ~ 6 之间'
    }
  ],
  age: [
    {
      validator: 'required',
      msg: '必填'
    },
    {
      validator: val => +val >= 20,
      msg: '长度在 2 ~ 6 之间'
    }
  ]
}

const validator = new Validator(formData, ruleConfig)
// 单个字段校验是否通过
validator.isError('age') // true | false
// 单个字段校验 (不传要校验的字段则默认校验全部)
validator.verify('age')
// 整体校验
validator.verify()

扩展默认规则

import Validator, { rules } from '@ignorance/validator'

rules.extendRegexp({
  onlyNumber: /^\d+$/,
  // ...
})

rules.extendValidator({
  lessThanTen: val => {
    val = +val
    return val < 10
  },
  // ...
})

About

JS 通用校验工具

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published