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.
npm install dvalidator --save
npm install @babel/plugin-proposal-decorators --save-dev
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)
})
arguments structure, describe with typescript interface.