sideway/joi js 强大的data schma 校验框架
数据校验处理在实际中是一个很重要的东西,类似的框架也比较多,同时也包含了好多规范指南(json schema,xml schema。。。。),joi 是一个比较强大的js 对于校验框架,使用简单,支持特新丰富
参考使用
const Joi = require('joi');
const schema = Joi.object({
username: Joi.string()
.alphanum()
.min(3)
.max(30)
.required(),
password: Joi.string()
.pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),
repeat_password: Joi.ref('password'),
access_token: [
Joi.string(),
Joi.number()
],
birth_year: Joi.number()
.integer()
.min(1900)
.max(2013),
email: Joi.string()
.email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })
})
.with('username', 'birth_year')
.xor('password', 'access_token')
.with('password', 'repeat_password');
schema.validate({ username: 'abc', birth_year: 1994 });
// -> { value: { username: 'abc', birth_year: 1994 } }
schema.validate({});
// -> { value: {}, error: '"username" is required' }
// Also -
try {
const value = await schema.validateAsync({ username: 'abc', birth_year: 1994 });
}
catch (err) { }
说明
joi 早期属于hapi 框架的,后边拆分出去了,是一个很不错的数据schema 处理框架