[node] joi数据校验模块

版权声明:本文为博主原创文章,未经博主允许不得转载。github仓库:https://github.com/lzcwds,欢迎访问 https://blog.csdn.net/lzcwds/article/details/82660091

前言

    在用nodejs时,需要对用户输入的数据进行验证。在前端做验证时,我们常用的做法是使用正则,正则表达式也许可以一步到位,但是他只会给你true or false,如果想要知道数据不符合哪些条件时,那么你要进一步判断,下面和大家分享一种可读性和易用性更好的实现方法。

Joi简介

    Joi是hapijs提供的数据检验插件,与 hapi一样出自沃尔玛实验室团队。Joi 的 API 因其丰富的功能,使得验证数据结构与数值的合规,变得格外容易。

1.安装
npm i joi
2.使用
const Joi = require('joi');

const schema = Joi.object().keys({
    username: Joi.string().alphanum().min(3).max(30).required(),
    password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/),
    access_token: [Joi.string(), Joi.number()],
    birthyear: Joi.number().integer().min(1900).max(2013),
    email: Joi.string().email({ minDomainAtoms: 2 })
}).with('username', 'birthyear').without('password', 'access_token');

// Return result.
const result = Joi.validate({ username: 'abc', birthyear: 1994 }, schema);
//result:{ error: null,
//  value: { username: 'abc', birthyear: 1994 },
//  then: [Function: then],
//  catch: [Function: catch] 
//}

除了对象Object以外,还有一些js的基本数据类型也支持。

const Joi = require('joi');
//number类型
const schema = Joi.number();

let result = Joi.validate('213aa',schema);
//或者 
//let result = schema.validate('213aa');
console.log(result);
//不符合类型,error有值
//result:{ error:
//   { ValidationError: "value" must be a number at Object.exports.process 
//   .....
//  value: NaN,
//  then: [Function: then],
//  catch: [Function: catch] 
//  }

更多的数据类型、方法看官方文档:https://github.com/hapijs/joi/blob/v13.6.0/API.md

3.浏览器

Joi并不直接支持浏览器,但可以将joi-browser用于在浏览器中运行的Joi的ES5版本。

猜你喜欢

转载自blog.csdn.net/lzcwds/article/details/82660091