eggjs&sequelize uses Tutorial 1 (Form Auto-Validation)

egg form form validation

A total of three files

1.Validate.config.jsMainly configure formateError: is the structure returned when customizing errors, default sets the corresponding error code

module.exports = {
    formateError: null,
    defaultMsg: {
        required: 'missing filed',
        isReg: 'not match',
        notReg: 'match',
        isEmail: 'not email',
        isUrl: 'not url',
        isIP: 'not IP',
        isAlpha: 'not all letter',
        isAlphanumeric: ' not letter or number',
        isNumeric: 'not a number',
        isInt: 'not int number',
        isFloat: 'not float number',
        isLowercase: 'letters are not small letter',
        isUppercase: 'letters are not big letter',
        notNull: 'not allow null',
        isNull: 'must be null',
        notEmpty: 'string not allow empty',
        contains: 'not contain require letters',
        notIn: 'is in required array',
        isIn: 'not in required array',
        len: 'the length is out of bounds',
        max: 'the number bigger than max value',
        min: 'the number samller than min value',        
    }   
}

2.Validate.jsValidated object, all validation methods are in it, can be self-expanding

3. Test filesValidate.test.js

Example

const validate = require('./validate.js');
const assert = require('assert');
require('should');
function getInstance(){
    return new validate({
            // formateError:function(err){
            //     return err;
            // }
    });
}
function check(rule,key,ruleName,data,ResultBoolean){
    if(ResultBoolean===true){
        let instance = getInstance();
        let result = instance.validate(rule,data);
        assert.equal(result, true);
        assert.equal(instance.errors.length,0);        
    }else{
        let instanceFalse = getInstance();
        let resultFalse = instanceFalse.validate(rule,data);
        assert.equal(resultFalse, false);
        assert.equal(instanceFalse.errors.length,1);
        instanceFalse.errors[0].should.have.property('msg',rule[key][ruleName].msg);
        instanceFalse.errors[0].should.have.property('filed').equal(key);        
    }

    // validate false

    // instance.should.have.propertyByPath('errors',0,'filed').equal('name');    
}
it('required',function(){
    let rule =  { name: { required:{args:true,msg:'required'}} };
    let myCheck= check.bind(null,rule,'name','required');
    myCheck({name:'ac'},true);
    myCheck({names:'ac2'},false);  
});

Run tests
Install the appropriate packages yourself

# mocha validate.test.js

How to use it in egg

Create form-under app/middelware Validate.js

module.exports = app => {
    return async function formValidate(rule,ctx,next) {     
        const validate = new ctx.app.validate();
        const requireFiled = Object.getOwnPropertyNames(rule);
        let form = {};
        if(ctx.method=='POST'){
            let queryFiled = Object.getOwnPropertyNames(ctx.request.body);
            for(let queryKey of queryFiled){
                if(requireFiled.indexOf(queryKey)==-1){
                    delete ctx.request.body[queryKey];
                }
            }
            form = ctx.request.body;
        }else{
            let queryFiled = Object.getOwnPropertyNames(ctx.request.query);
            for(let queryKey of queryFiled){
                if(requireFiled.indexOf(queryKey)==-1){
                    delete ctx.request.query[queryKey];
                }
            }            
            form = ctx.request.query;
        }
        if(validate.validate(rule,form) === false){
            return ctx.setReturn(app.code.formError,validate.errors);
        }
        await next();
    }
}

validate.validate(rule,form) mask is to validate the form, preceded by just distinguishing get from post and eliminating redundant form items
rule is the variable that is passed in from the route

Writing Routes

module.exports = app => {
  const { router } = app;
  let formValidate = app.middlewares.formValidate(app);
  let { testFormRule,loginForm } = require('./form/form-rule')(app);
  router.get('/', formValidate.bind(null,testFormRule), 'home.index');

  router.post('/api/login',formValidate.bind(null,loginForm),'login.login');
};

loginForm

module.exports = app => {
    const loginForm = {
        username: {
            required: {
                args: true,
                msg: app.code.usernameNotNull
            },
            notEmpty: {
                args: true,
                msg: app.code.usernameNotNull
            }
        },
        password: {
            required: {
                args: true,
                msg: app.code.passwordNotAllowNull
            },
            notEmpty: {
                args: true,
                msg: app.code.passwordNotAllowNull
            }
        }
    };
    return loginForm;
}

When the error is returned, the error structure is [{filed:'username',msg:501}]
Specific code location

Posted on Thu, 16 Jul 2020 10:56:23 -0400 by callesson