UserForm Validation with wtforms

  • Share this:

Code introduction


This function defines a class named UserForm, which inherits from the Form class of the wtforms library. UserForm contains two fields: username and email, defined by the StringField class and applied with length and email validators. The validate_form function is used to validate the form data.


Technology Stack : Python, wtforms

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
from wtforms import Form, StringField, validators

def random_form_function():
    class UserForm(Form):
        username = StringField('Username', [validators.Length(min=4, max=25)])
        email = StringField('Email', [validators.Length(min=6, max=35), validators.Email()])

    def validate_form():
        form = UserForm(username='john_doe', email='john@example.com')
        if form.validate():
            print("Form is valid.")
        else:
            print("Form is invalid.")

    return validate_form

validate_form = random_form_function()                
              
Tags: