Current Size:
Chakra BreakPoints
base0px
sm480px
md768px
lg992px
xl1280px
2xl1536px
Current Height:Width
widthpx
heightpx

Subjects

Express Validation Patterns

Date Created: 2022/02/22

Last Update: 2022/12/15

#validation #express #notes #moc

Approved Starters

Express Frameworks

Express Validation

Package Install

npm i express-validator

Example -inline

index.js

//...
const { validationResult, body } = require("express-validator")
//...
const app = express()
//...
//... validator example
app.post("/users", [
body("email")
.isLength({ min: 1 })
.withMessage("email must not be empty")
.isEmail()
.withMessage("must be a valid email address"),
body("name").isLength({ min: 1 }).withMessage("name must not be empty"),
]),
async (req, res) => {
const errors = validationResult(req)
if (!errors.isEmpty) {
return res.status(400).json(errors.mapped())
}
}

Example - abstracted

index.js

//...
const { validationResult, body } = require("express-validator")
//...
const app = express()
const userValidation = [
body("email")
.isLength({ min: 1 })
.withMessage("email must not be empty")
.isEmail()
.withMessage("must be a valid email address"),
body("name").isLength({ min: 1 }).withMessage("name must not be empty"),
]
//... validation middleware
const checkForErrors = (req, res, next) => {
const errors = validationResult(req)
if (!errors.isEmpty) {
return res.status(400).json(errors.mapped())
} else {
next()
}
}
const simpleValiationResult = validationResult.withDefaults({
formatter: (err) => err.msg,
})
//...
//... validator example
app.post("/users", userValidation, checkForErrors),
async (req, res) => {
try {
return res.status(200).json({ message: "valid input" })
} catch (err) {
return res.status(500).json(err)
}
}

More Notes

All Notes
HomeProjects

Links

Home Articles Notes Projects About Style Guide Site Credits

Contact

 [email protected]

Location

🌎 Earth