'Flask-html : Best way to validate form input
Hello I'm trying to create a web registration form with the flask module. What is the easiest way/module to check if a username contains a certain amount of characters, has numbers, and uppercase letters and how do I loop a form input until a valid username in this case is entered?
@app.route('/register', methods=['POST', 'GET'])
def register():
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
error = None
if not username:
error = "Username is required."
elif not password:
error = "Password is required."
flash(error)
if error is None:
with open('data.txt', 'a', encoding='utf8') as file:
encoded_password = password.encode()
hash_password = hashlib.sha256(encoded_password).hexdigest()
file.write(username + ' ' + hash_password + '\n')
return redirect(url_for("login"))
return render_template('register.html')
Solution 1:[1]
call another function like this (just an example only worrying about the username) and expand the logic as you see fit - determine if they should stay on the registration page based on whether process_registration is True
def verify_user_registration_credentials(username, password):
if not username:
flash_message = "Please enter a username"
process_registration = False
elif len(username) <= 5:
flash_message = "Please enter a username greater than 5 characters"
process_registration = False
else:
for character in username:
if character.isdigit() or character.isupper():
break
process_registration = True # assuming you want them to have either a number or an upper case letter in their username
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DanielJerrehian |
