Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't figure out why code is skipping over if statements in javascript

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading