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

Subjects

Express Validation Patterns

#validation #express #notes #moc

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

Links

Home Articles Notes Projects About Style Guide Site Credits

Contact

 [email protected]

Location

🌎 Earth