使用 E6S 编写的一个类似 laravel 的 js 验证模块.
$ npm install validation-es6
import {
Validator
} from './node_modules/validation-es6/validator.js';
let rules = {
username: 'required|min:5',
password: 'required|confirmed|min:6|max:16',
}
let data = {
username: 'test',
password: '123456',
}
let v = new Validator(data, rules);
if (v.fails()) {
console.log(v.messages());
}
let rules = {
username: 'required|min:5',
password: 'required|confirmed|min:6|max:16',
email: 'email'
}
let rules = {
username: ['required', 'min:5'],
password: ['required', ['confirmed'], ['min:6'], ['max:16'],
email: ['required', 'email']
}
在消息字符串用使用
:attribute
作为属性名占位符。
//错误消息
let customMessages = {
accepted: ":attribute 必须接受",
};
//属性别名
let attribute = {
"item": "条款"
}
//使用回调函数定义错误消息
let replacers = {
accepted: function (message, attribute, rule,parameters) {
return message;
}
},
let v = new Validator(data, rules, customMessages, attribute, replacers);
//注册自定义验证函数
v.register('upper', (attribute, value, parameters) => {
return value.toUpperCase() == "NAME";
}, ":attribute = :value 不对");
if (v.fails()) {
console.log(v.messages());
}
1
Cbdy 2019-06-22 21:31:09 +08:00 via Android
为什么不用 joi
|