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

Alternative to Nested if statements Flask

Summary

I have built a flask application thats taken several inputs from the user and the inputs need to be verified to certain criteria. If the inputs are not verified correctly, a flash message will show depicted what is incorrect of the input.

The home page has 4 nested if statements which displays certain messages based on the in correct result.

Python code

if request.method == 'POST':

        VM = request.form['email'] 
        RM = request.form['mobile']

        if isEmailInUse(VM):

            if VM not in blacklist and VM.endswith("@gmail.com"):

                if len(RM) == 11 and RM.startswith("555"):

                    create(user)

                    return redirect(url_for('see_users'))

                else:
                    flash('Invalid mobile! ', 'error')

            else:
                flash('Invalid Email Address! ', 'error')

        else:
            flash('Email Address already in use. ', 'error')

return render_template('Validate_Email.html')

I have tried

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

if VM not in blacklist and VM.endswith("@gmail.com"): flash('Invalid Email Address! ', 'error')

but it continues on with the code.

Is there an alternative to having so many nested ifs in flask to verify user input with flask messages?

some guidance or assistance would be much appreciated!

>Solution :

Reverse the order of the tests and negate the logic, as needed, for example:

if request.method == 'POST':
    VM = request.form['email']
    RM = request.form['mobile']

    if not checkinUse(VM):
        flash('Email Address already in use. ', 'error')
    elif if VM in blacklist or not VM.endswith("@gmail.com"):
        flash('Invalid Email Address! ', 'error')
    elif len(RM) != 11 or not RM.startswith("555")
        flash('Invalid mobile! ', 'error')
    else:
        create(user)
        return redirect(url_for('see_users'))

return render_template('Validate_Email.html')

PS checkinUse seems to be a questionable choice of name for a function that returns True if an email address is not in use.

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