当前位置: 首页 > 后端技术 > Node.js

NPM酷库043:joi,语义模式验证

时间:2023-04-03 13:20:59 Node.js

NPM酷库,每天两分钟了解一个流行的NPM库。·在NPM酷库042中,我们了解了JSONSchema数据模式验证和ajv库。今天我们来学习另一个对象数据校验库joi。joijoi是一个语义对象数据模型验证库。所谓语义化,就是它的方法名能够清楚地表达它的意思。constJoi=require('joi');//声明模式constschema=Joi.object().keys({username:Joi.string().alphanum().min(3).max(30).required(),密码:Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/),access_token:[Joi.string(),Joi.number()],生日:Joi.number().integer().min(1900).max(2013),email:Joi.string().email()}).with('username','birthyear').without('password','access_token');//Validateconstresult=Joi.validate({username:'abc',birthyear:1994},schema);//result.error===null->valid注意:joi不是JSONSchema标准实现,另外,使用ajv验证JSONSchema可以将schema配置信息保存在.json文件中,因为JSONSchemaschema是声明式的,joi必须在代码文件中实现schema配置,因为joi的语义必须通过函数调用实现。参考资料https://github.com/hapijs/joihttps://github.com/hapijs/joi...