Registration Form with WTForms and Password Validation

  • Share this:

Code introduction


This code defines a registration form using the wtforms library to create form fields and perform validations. It includes username, email, and password fields, with a validation for the password length.


Technology Stack : wtforms

Code Type : Form Validation

Code Difficulty : Intermediate


                
                    
from wtforms import Form, StringField, PasswordField, validators

def validate_password_length(form, field):
    if len(field.data) < 8:
        raise validators.ValidationError('Password must be at least 8 characters long.')

def create_registration_form():
    class RegistrationForm(Form):
        username = StringField('Username', [validators.Length(min=4, max=25)])
        email = StringField('Email', [validators.Length(min=6, max=35)])
        password = PasswordField('Password', [
            validators.DataRequired(),
            validate_password_length
        ])

    return RegistrationForm()                
              
Tags: