Skip to content

Latest commit

 

History

History
66 lines (52 loc) · 1.35 KB

README_en.md

File metadata and controls

66 lines (52 loc) · 1.35 KB

dvalidator

A pure, extendable, very useful validator base Promise and Decorator

  • Object literals : Base es7 Decorator, we can add a decorator on a object literals. Dvalidator will add some unenumerable keys to store rules.
  • Asynchronous : dvalidator support async validator function
  • Ordered : When you call $validate function, dvalidator will exec validator function in ordered.

Install

npm install dvalidator --save
npm install @babel/plugin-proposal-decorators --save-dev

Usage

config babel.config.js

plugins: [
  [
    '@babel/plugin-proposal-decorators',
    {
      legacy: true
    }
  ]
]

For example, we validate a user object.
nickname and phone is required, also phone is validate from remote server.
import dvalidator from 'dvalidator'

const requiredRule = {
  validator: val => val != null && val !== '',
  message: 'required'
}
const required = dvalidator(requiredRule)
const checkPhone = dvalidator(value => fetch(`xxx/${value}`))

const user = {
  @required('nickname is required')
  nickname: '',
  @checkPhone('phone valid fail')
  @required
  phone: ''
}

user
  .$validate()
  .then(/* success */)
  .catch(reason => {
    /* fail */
    alert(reason[0].message)
  })

Interface

arguments structure, describe with typescript interface.