I am working with forms in Express.js and I am using express-validator for validation. The code I have shown below is a "form" with two text boxes, a choose file button and a submit button. When the user submits the form, but there are validation errors I would like to:
Show an error message, saying which of the elements in the form the user needs to fill in. I believe I know how to do this with pop-up windows, but I would like to know if there is a way to "highlight" the text box that the user is required to fill in, or put a "* Required" text next to the text box/button.
Currently, if there are errors, after the submission, the two text boxes in the form are populated with the variables that were previously submitted by the user. I would like to do the same thing for the "Choose file" button. Using the "value" field as I have done in the two text boxes, does not work for the button. Is there way to do this?
//in routes folder
exports.myPage = function(req, res) {
res.render('myPage.jade', {valName: 'Enter', valLastName: 'Enter'});
};
exports.myPage_post_handler = function(req, res) {
nameID = req.body.nameID;
lastNameID = req.body.lastNameID;
my_file = req.body.my_file;
req.session.nameID = nameID;
req.session.lastNameID = lastNameID;
req.session.my_file = my_file;
if (typeof req.session.nameID != 'undefined'){
valName = nameID;
}
if (typeof req.session.lastNameID != 'undefined'){
valLastName = lastNameID;
}
req.assert('nameID', 'Please enter a name').notEmpty();
req.assert('lastNameID', 'Please enter a last name').notEmpty();
req.assert('my_file', 'Please enter a my_file').notEmpty();
var errors = req.validationErrors();
if( !errors){
res.redirect('/other_page');
}
else {
res.render('myPage.jade');
}
};
//in my_page.jade
form(method='post')
| Name:
div
input(type='text', name='nameID', id = 'name', value = valName)
| Session ID:
div
input(type='text', name='laastNameID', id ='lastName', value = valLastName)
| Video:
div
input(type='file', name='my_file', id='fileF')
div
input(type='submit', value='submit', value='Submit')
In Html5 (which also applies to Jade) you can put a "required" parameter whenever you declare text boxes or radio buttons etc..