Say you have a POST endpoint that accepts the name, email and age parameters:
假设您有一个POST端点,可以接受名称,电子邮件和年龄参数:
const express = require('express')
const app = express()
app.use(express.json())
app.post('/form', (req, res) => {
const name = req.body.name
const email = req.body.email
const age = req.body.age
})
How do you perform server-side validation on those results to make sure:
如何对这些结果执行服务器端验证,以确保:
The best way to handle validation on any kind of input coming from outside in Express is by using the express-validator
package:
处理Express中来自外部的任何输入的验证的最佳方法是使用express-validator
包 :
npm install express-validator
You require the check
and validationResult
objects from the package:
您需要包装中的check
和validationResult
对象:
const { check, validationResult } = require('express-validator');
We pass an array of check()
calls as the second argument of the post()
call. Every check()
call accepts the parameter name as argument. Then we call validationResult()
to verify there were no validation errors. If there are any, we tell them to the client:
我们传递一个check()
调用数组作为post()
调用的第二个参数。 每个check()
调用均接受参数名称作为参数。 然后我们调用validationResult()
来验证没有验证错误。 如果有的话,我们告诉他们:
app.post('/form', [
check('name').isLength({ min: 3 }),
check('email').isEmail(),
check('age').isNumeric()
], (req, res) => {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() })
}
const name = req.body.name
const email = req.body.email
const age = req.body.age
})
Notice I used
注意我用过
isLength()
isLength()
isEmail()
isEmail()
isNumeric()
isNumeric()
There are many more of these methods, all coming from validator.js, including:
这些方法还有很多,全部来自validator.js ,包括:
contains()
, check if value contains the specified value
contains()
,检查value是否包含指定的值
equals()
, check if value equals the specified value
equals()
,检查value是否等于指定的值
isAlpha()
isAlpha()
isAlphanumeric()
isAlphanumeric()
isAscii()
isAscii()
isBase64()
isBase64()
isBoolean()
isBoolean()
isCurrency()
isCurrency()
isDecimal()
isDecimal()
isEmpty()
isEmpty()
isFQDN()
, is a fully qualified domain name?
isFQDN()
,是完全限定的域名吗?
isFloat()
isFloat()
isHash()
isHash()
isHexColor()
isHexColor()
isIP()
isIP()
isIn()
, check if the value is in an array of allowed values
isIn()
,检查该值是否在允许值的数组中
isInt()
isInt()
isJSON()
isJSON()
isLatLong()
isLatLong()
isLength()
isLength()
isLowercase()
isLowercase()
isMobilePhone()
isMobilePhone()
isNumeric()
isNumeric()
isPostalCode()
isPostalCode()
isURL()
isURL()
isUppercase()
isUppercase()
isWhitelisted()
, checks the input against a whitelist of allowed characters
isWhitelisted()
,根据允许的字符白名单检查输入
You can validate the input against a regular expression using matches()
.
您可以使用matches()
根据正则表达式验证输入。
Dates can be checked using
可以使用检查日期
isAfter()
, check if the entered date is after the one you pass
isAfter()
,检查输入的日期是否在您通过的日期之后
isBefore()
, check if the entered date is before the one you pass
isBefore()
,检查输入的日期是否在您通过的日期之前
isISO8601()
isISO8601()
isRFC3339()
isRFC3339()
For exact details on how to use those validators, refer to https://github.com/chriso/validator.js#validators.
有关如何使用这些验证器的确切详细信息,请参阅https://github.com/chriso/validator.js#validators 。
All those checks can be combined by piping them:
所有这些检查可以通过以下方式组合使用:
check('name')
.isAlpha()
.isLength({ min: 10 })
If there is any error, the server automatically sends a response to communicate the error. For example if the email is not valid, this is what will be returned:
如果有任何错误,服务器将自动发送响应以传达错误。 例如,如果电子邮件无效,将返回以下内容:
{
"errors": [{
"location": "body",
"msg": "Invalid value",
"param": "email"
}]
}
This default error can be overridden for each check you perform, using withMessage()
:
可以使用withMessage()
执行的每个检查覆盖此默认错误:
check('name')
.isAlpha()
.withMessage('Must be only alphabetical chars')
.isLength({ min: 10 })
.withMessage('Must be at least 10 chars long')
What if you want to write your own special, custom validator? You can use the custom
validator.
如果您想编写自己的特殊定制验证器怎么办? 您可以使用custom
验证器。
In the callback function you can reject the validation either by throwing an exception, or by returning a rejected promise:
在回调函数中,您可以通过引发异常或返回被拒绝的承诺来拒绝验证:
app.post('/form', [
check('name').isLength({ min: 3 }),
check('email').custom(email => {
if (alreadyHaveEmail(email)) {
throw new Error('Email already registered')
}
}),
check('age').isNumeric()
], (req, res) => {
const name = req.body.name
const email = req.body.email
const age = req.body.age
})
The custom validator:
定制验证器:
check('email').custom(email => {
if (alreadyHaveEmail(email)) {
throw new Error('Email already registered')
}
})
can be rewritten as
可以改写成
check('email').custom(email => {
if (alreadyHaveEmail(email)) {
return Promise.reject('Email already registered')
}
})