As a beginner with Express and Sequelize, I am looking to utilize Sequelize's validation functionality for form submissions without having to duplicate validations on the frontend or rely on additional libraries like express-validator. Below is an example of what I am trying to achieve:
var signup = function(req, res) {
res.render('signup', { title: 'Sign-up' });
}
router.get('/signup', signup);
router.post('/signup', function(req, res) {
User.create({
email: req.body.email,
...
}).then(function(user) {
req.flash('info', 'User created successfully.');
res.redirect('/login');
}).catch(function(err) {
// [1] Need a solution to convert Sequelize error messages into a JSON object
if (req.xhr) {
res.json(err);
}
else {
// [2] Alternative for non-JS browsers
req.flash('error', err);
signup(req, res);
}
});
});
- How can I efficiently handle [1] without manually formatting Sequelize error messages into JSON?
- What approach should be taken to process the JSON on the frontend in order to highlight fields with errors without manual intervention for each field?
- What is the recommended method to repopulate the form with submitted data? Despite extensive online searches, information on this topic is scarce and most sources suggest manually setting the value attribute in the template (which becomes cumbersome with various types of input fields). While AJAX submission may solve this issue, forms should ideally function without JavaScript as well in my opinion.
Thank you!