egg-joi-new
v1.1.3
Published
a validator with @hapi/joi for egg.js
Downloads
34
Maintainers
Readme
egg-joi-new
- 改进自egg-joi, 使用最新版的@hapi/joi ,并且添加了中文提示支持~
- Improved from egg-joi, using the latest version of @ hapi / joi, and added Chinese hint support
Install
$ npm i egg-joi-new --save
Usage
// {app_root}/config/plugin.js
exports.joi = {
enable: true,
package: 'egg-joi-new',
};
Configuration
// {app_root}/config/config.default.js
exports.joi = {
options: {},
locale: {
'zh-cn': true, // if you don't need error message with chinese ,you can set to false
},
throw: true, // throw error when capture exception
throwHandle: error => { // when throw is true the error message format
return error;
},
errorHandle: error => { // when throw is false the error message format
return error;
},
resultHandle: result => { // fromat result
return result;
},
};
Example
app/validator/sessions
'use strict';
module.exports = app => {
const Joi = app.Joi;
return {
login: Joi.object().keys({
email: Joi.string().email(),
password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/)
})
}
};
app/controller/sessions
'use strict';
module.exports = app => {
class SessionsController extends app.Controller {
async login() {
this.ctx.validate(app.validator.sessions.login, this.ctx.request.body); // if get error, ctx.body will be return
this.body = 'hello';
}
}
return SessionsController;
};