wtforms-based User Registration Form Validation

  • Share this:

Code introduction


This code uses the wtforms library and its components such as Form, StringField, PasswordField, BooleanField, and validators like InputRequired, Length, Email, Regexp, and EqualTo.


Technology Stack : 代码所使用到的包和技术栈[英文]

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
from wtforms import Form, StringField, PasswordField, BooleanField
from wtforms.validators import InputRequired, Length, Email, Regexp, EqualTo

def validate_username(username):
    if len(username) < 3 or len(username) > 15:
        raise ValueError("Username must be between 3 and 15 characters.")

def validate_password(password):
    if len(password) < 6:
        raise ValueError("Password must be at least 6 characters long.")

def create_user_registration_form():
    class RegistrationForm(Form):
        username = StringField('Username', validators=[InputRequired(), Length(min=3, max=15), validate_username])
        email = StringField('Email', validators=[InputRequired(), Email(message="Invalid email address")])
        password = PasswordField('Password', validators=[InputRequired(), Length(min=6, message="Password must be at least 6 characters long")])
        confirm_password = PasswordField('Confirm Password', validators=[InputRequired(), EqualTo('password', message="Passwords must match")])

    return RegistrationForm()