Home > other >  Alternative to Nested if statements Flask
Alternative to Nested if statements Flask

Time:02-16

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

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!

CodePudding user response:

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.

  • Related