joi 参数验证
Imagine you have an e-commerce website and you’re allowing users to create accounts using their name and email. You want to make sure they sign up with real names, not something like cool_dud3.
假设您有一个电子商务网站,并且允许用户使用其名称和电子邮件创建帐户。 您要确保他们使用真实姓名注册,而不要使用cool_dud3之类的名称。
That's where we use validation to validate inputs and make sure input data follows certain rules.
那是我们使用验证来验证输入并确保输入数据遵循某些规则的地方。
In the market, we already have a bunch of validation libraries, but I will compare two important validation libraries: Joi and express-validator for express.js based applications.
在市场上,我们已经有很多验证库,但是我将比较两个重要的验证库: Joi和基于express.js的应用程序的 express-validator 。
This comparison is useful when you have decided to use external input validation library for your application built on expressjs and are somewhat not sure which one to use.
当您决定对构建在expressjs上的应用程序使用外部输入验证库,并且不确定使用哪个输入验证库时,此比较很有用。
谁啊 (Who is what?)
i (Joi)
Joi allows you to create blueprints or schemas for JavaScript objects (an object that stores information) to ensure validation of key information.
Joi允许您为JavaScript对象(存储信息的对象)创建蓝图或架构 ,以确保验证关键信息。
快速验证器 (Express-validator)
express-validator is a set of express.js middlewares that wraps validator.js validator and sanitizer functions.
express-validator是一组express.js中间件,其中包装了validator.js验证器和消毒器功能。
So by definition, we can say that:
因此,根据定义,我们可以这样说:
- Joi can be used for creating schemas (just like we use mongoose for creating NoSQL schemas) and you can use it with plain Javascript objects. It's like a plug n play library and is easy to use. Joi可用于创建架构(就像我们使用猫鼬创建NoSQL架构一样),并且您可以将其与普通Javascript对象一起使用。 它就像一个即插即用库,并且易于使用。
On the other hand, express-validator uses validator.js to validate expressjs routes, and it's mainly built for express.js applications. This makes this library more niche and provides out of box custom validation and sanitization. Also, I find it easy to understand personally :)
另一方面, express-validator使用validator.js来验证expressjs路由,它主要是为express.js应用程序构建的。 这使该库更具优势,并提供了开箱即用的自定义验证和清理功能。 另外,我觉得很容易亲自理解:)
Too many methods and API's for doing certain validation in Joi might make you feel overwhelmed so you might end up closing the tab.
在Joi中执行某些验证的方法和API太多,可能会让您感到不知所措,因此最终可能会关闭选项卡。
But I may be wrong — so let’s keep opinions aside and compare both libraries.
但是我可能是错的,所以让我们把意见放在一边,比较两个库。
实例化 (Instantiation)
i (Joi)
In Joi, you need to use Joi.object()
to instantiate a Joi schema object to work with.
在 Joi ,您需要使用Joi.object()
实例化要使用的Joi模式对象。
All schemas require Joi.object()
to process validation and other Joi features.
所有模式都需要Joi.object()
来处理验证和其他Joi功能。
You need to separately read req.body
, req.params
, req.query
to request body, params, and query.
您需要分别阅读req.body
, req.params
, req.query
来请求主体,参数和查询。
const Joi = require('joi');
const schema = Joi.object().keys({
// validate fields here
})