From 5ed4787e33e258cc9afa7e9d2886a0b590d69715 Mon Sep 17 00:00:00 2001 From: Mateja Date: Sun, 9 May 2021 14:41:41 +0200 Subject: Returning validation errors and old values to `post` form. Made custom middleware for that purpose. --- utils/middleware/oldForm.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 utils/middleware/oldForm.js (limited to 'utils/middleware/oldForm.js') diff --git a/utils/middleware/oldForm.js b/utils/middleware/oldForm.js new file mode 100644 index 0000000..7bcfb34 --- /dev/null +++ b/utils/middleware/oldForm.js @@ -0,0 +1,23 @@ +module.exports = (req, res, next) => { + + req.setOldForm = (errors) => { + let prettyErrors = {}; + Object.keys(errors.errors).forEach(err => { + prettyErrors[err] = errors.errors[err].message; + }); + + req.session.oldForm = { + errors: prettyErrors, + values: req.body + }; + }; + + if (!req.session.oldForm) req.session.oldForm = { + errors: null, + values: null + }; + + res.locals.oldForm = req.session.oldForm; + delete req.session.oldForm; + next(); +}; -- cgit v1.2.3