let emptyErr = []
if (!(req.files || req.files.image)) {
emptyErr[0] = ('An image banner is required for a post!')
}
else if (!req.body.title) {
emptyErr[1] = ('A title is required for a post.')
}
else if (!req.body.body) {
emptyErr[2] = ('Content is required for a post.')
}
else if (emptyErr.length > 0) {
req.flash('validationErrors', emptyErr)
res.redirect('/post/new')
}
let image = req.files.image
If I leave the form completely blank, it should check each of these if statements and add a string to the array at the top. Then it would check if there are any elements in the array and redirect to a different page, killing the script. But instead it just skips over the if statements and then complains that the req.files.image
is null. Which if it was null, it would trigger the first if statement, add an element to the array and hit the last if statement. I'm not too sure why this is happening and what I'm doing wrong.
CodePudding user response:
You want if not else if
by doing what you do, javascript doesn't go inside else if or else if the parent if or if one else if match the condition.
let emptyErr = []
if (!(req.files || req.files.image)) {
emptyErr.push('An image banner is required for a post!')
}
if (!req.body.title) {
emptyErr.push('A title is required for a post.')
}
if (!req.body.body) {
emptyErr.push('Content is required for a post.')
}
if (emptyErr.length > 0) {
req.flash('validationErrors', emptyErr)
res.redirect('/post/new')
}
let image = req.files.image
Also use .push() to add something in the array, else if one if is not correct you will have an incorrect array since index will be empty.