express-yup-middleware is an express middleware that uses Yup schemas to validate a request and return a response with errors.
import { expressYupMiddleware } from 'express-yup-middleware'
import * as Yup from 'yup'
const schemaValidator = {
schema: {
query: {
yupSchema: Yup.object().shape({
testQueryParam: Yup.string().required('requiredTestQueryParam'),
}),
},
body: {
yupSchema: Yup.object().shape({
testBodyProperty: Yup.string().required('requiredTestBodyProperty'),
}),
},
params: {
yupSchema: Yup.object().shape({
testParams: Yup.string().required('requiredTestParams'),
}),
},
},
}
app.post('/test', expressYupMiddleware({ schemaValidator }))
{
"errors": {
"params": [
{
"message": "requiredTestParams",
"propertyPath": "testParams"
}
],
"body": [
{
"message": "requiredTestBodyProperty",
"propertyPath": "testBodyProperty"
}
],
"query": [
{
"message": "requiredTestQueryParam",
"propertyPath": "testQueryParam"
}
]
}
}
Make sure the key in the Yup schema (requiredTestBodyProperty) matches the property name in the error messages object.
const schemaValidator = {
schema: {
body: {
yupSchema: Yup.object().shape({
testBodyProperty: Yup.string().required('requiredTestBodyProperty'),
}),
},
},
errorMessages: {
requiredTestBodyProperty: {
key: 'tes-body-property-required',
message: 'The "testBodyProperty" property is required!',
},
},
}
{
"errors": {
"body": [
{
"key": "tes-body-property-required",
"message": "The \"testBodyProperty\" property is required!",
"propertyPath": "testBodyProperty"
}
]
}
}
You can cross-validate properties of your payload using a custom Yup test and accessing them by calling this.options.context
.
const schemaValidator = {
schema: {
body: {
yupSchema: Yup.object().shape({
numberToValidate: Yup.string().test({
message: 'Check if your number corresponds with the given type',
test(this: Yup.TestContext, numberToValidate: any) {
const mod = numberToValidate % 2
// As you can see in the next line, the req is passed to the context
const type = this.options.context['payload'].params.type
if (!type) {
return false
}
if (type === 'even') {
return mod === 0
}
if (type === 'odd') {
return mod !== 0
}
return false
},
}),
}),
},
},
}
app.post('/test/:type', expressYupMiddleware({ schemaValidator }))
The middleware default properties checked in the req
(Express request) are body, params and query. If you want to validate anything else, you need to use the following option.
const schemaValidator = {
schema: {
headers: {
yupSchema: Yup.object().shape({
testHeaderProperty: Yup.string().required('requiredHeaderProperty'),
}),
},
},
}
app.post('/test', expressYupMiddleware({ schemaValidator, propertiesToValidate: ['headers'] }))
{
"errors": {
"headers": [
{
"message": "requiredHeaderProperty",
"propertyPath": "testHeaderProperty"
}
]
}
}
Adding the expectedStatusCode
option, your will receive the given status code if anything fails during the validation.
app.post('/test', expressYupMiddleware({ schemaValidator, expectedStatusCode: 418 }))