Watch 1 Star 3 Fork 0

LonelYu / Koa-ValidatorNodeJSApache-2.0

Join us
Explore and code with more than 5 million developers,Free private repositories !:)
Sign up
帮助Koa开发者快速进行参数验证。Go! spread retract

Clone or download
Cancel
Notice: Creating folder will generate an empty file .keep, because not support in Git
Loading...
README.md

Koa-Validator

通过Koa-Validator可以快速验证前端向后端传入的参数,同时提供同一个验证器编写风格。(V0.0.1 目前开发和测试中,请谨慎使用)

验证器功能

参数验证

class Validator extends KoaValidator{
    constructor(){
        super();
        this.email = [new VRule('isEmail','当前字段非Email')];
        this.name = [new VRule('isString','当前字段必须是String类型',{min:3,max:5})];
    }
}
new Validator.validate()

验证别名

class Validator extends KoaValidator{
    constructor(){
        super();
        this.email = [new VRule('isEmail','当前字段非Email')];
        this.name = [new VRule('isString','当前字段必须是String类型',{min:3,max:5})];
    }
}
//就会使得name的验证改为去验证id字段
new Validator.validate({name:'id'});

自定义方法验证

自定义方法必须是以Validate加大写字母开头

validatePassword(vals) {
        const psw1 = vals.body.password1
        const psw2 = vals.body.password2
        if (psw1 !== psw2) {
            throw new Error('两个密码必须相同')
        }
    }

自定义Rule验证

通过扩展Rule类型自定义验证方法,可以自己终止验证链条从而可以满足选择验证,也可以调用基类的_allowNext方法传递上下文,从而可以继续验证

class isOptionRule extends Rule {
    constructor(msg, defaultValue) {
        super(msg);
        this.defaultValue = defaultValue;
    }
    validate(context) {
        if (field == null) {
            return new RuleFieldResult(true, '', this._getDefault());
        };
        this._allowNext(context);
    }
    _getDefault() {
        return this.defaultValue;
    }
}

中间件使用(开发ING)

正在开发和测试中…………

计划

  • 完成单元测试
  • 完成中间件调用验证

TIPS

验证调用顺序 isOptions优先于任何Rule验证,否则会出现逻辑错误。

Comments ( 0 )

Sign in for post a comment

NodeJS
1
https://gitee.com/ChronosAeon/Koa-Validator.git
git@gitee.com:ChronosAeon/Koa-Validator.git
ChronosAeon
Koa-Validator
Koa-Validator
master

Help Search

182353 aa51c838 1899542 205747 347fc4a1 1899542