Open In App

Create a Registration Form using PyWebIO Module in Python

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to create a registration form using the PyWebIO module. This is a Python module mostly used to create simple and interactive interfaces on the local web using Python Programming. 

This form will take username, name, password, email, website link as input. Talking about passwords, it will also check your password again to confirm whether your password is correct or not. It will also validate your phone number, website link, email address. After that, you will get the radio button consisting of Gender, and you will also get the comment section so that you can write your feedback.

Form Elements 

To create a proper form with validations we will learn different form elements one by one with examples.

1. input_group: This element is used to get the inputs in the group. When we use input_group, we need to provide the name parameter to each input function to identify the input items in the result.

Syntax: input_group(“Title”, [input(‘Any name’, name=’Anything’),input(‘Any name’, name=’Anything’)])

Python3




info = input_group("Group inputs", [
     input('Username', name='username'),
     input('Password', name='pass')])


Output: 

2. input: This element is used to take all kinds of inputs of the user from the browser.

Syntax: input(‘Some text’)

Python3




input("Your name")


Output: 

3. type: This is defined inside the input function or input_group function. This depends on user choice whether the user wants a number in the input or a text in the input. If the type equals the number, it will only accept numbers and a similar case for the text.

Syntax: 

input(‘Some text’, type=TEXT)

input(‘Some text’, type=NUMBER)

input(‘Some text’, type=PASSWORD)

Python3




input('Name', type=TEXT)
input('PIN', type=NUMBER)
input('Password', type=PASSWORD)


Output: 

4. required: If required is true, that means you have to input something, we can’t leave blank, otherwise, it will through an error called “Please fill out this field”. By default, it’s false.

Syntax: input(‘Some text’, required=True)

Python3




input('Name', required=True)


Output: 

5. validate: This element receives input as a parameter, when the input value is valid, it returns True, when the user input is invalid, it returns an error message.

Syntax: input(‘Some text’, validate=is_valid)

Python3




def is_valid(data):
    if data <= 0:
        return 'Age cannot be negative!'
  
input('Age', type=NUMBER, validate=is_valid)


Output: 

6. cancelable: Whether the form can be canceled. Default is False. If cancelable=True, a “Cancel” button will be displayed at the bottom of the form.

Syntax: input_group(“Title”, [input(‘Any name’, name=’Anything’),input(‘Any name’, name=’Anything’)], cancelable=True)

Python3




input_group("Info", [input('Name', name='name'),input('PIN ', name='pin')], cancelable=True)


Output: 

7. PlaceHolder: This element is used only in the input_group function, this is used to show a very light text.

Syntax: input(‘Some text’, placeholder=”some text”)

Python3




input('Name', placeholder="Please Enter your name")


Output: 

8. radio: The radio button is used when we have to choose only one option in the many options, i.e., only a single can be selected.

Syntax: radio(“Some text”, options=[‘Option 1’, ‘Option 2’])

Python3




radio("Gender", options=['Male', 'Female'])


Output: 

9. select:  This is also called Drop-Down selection. By default, only one option can be selected at a time. You can also select multiple options by setting the “multiple” parameter to True.

Syntax: select(“Some text”, options=[‘Option 1’, ‘Option 2’, ‘Option 3’, ‘Option 4’], multiple=True)

Python3




select("Tech Stack", options=[
  'C Programming', 'Python', 'Web Development', 'Android Development'])


Output: 

10. textarea: This element is used to take multi-line input in a text input area. The row is an element defined inside the textarea which is used for a number of visible text lines.

Syntax: textarea(“Some text”, rows=3)

Python3




textarea("Comments/Questions", rows=3)


Output: 

11. checkbox: The Checkbox allows users to select/deselect multiple values, we have to provide the options so that the user can select any values.

Syntax: checkbox(“Some text”, options=[‘Option 1’, ‘Option 2’, ‘Option 3’]) 

Python3




checkbox("Languages", options=['Hindi', 'English', 'French'])


Output: 

12. popup: The pop is used to produce output in a popup manner, multiple pops-ups can’t show at a time. Before displaying a new pop-up window, the existing popup on the page will be automatically closed or you can close manually.

Syntax: popup(“Title”, “Text”)

Python3




popup("Who are you?", "Geeks for Geeks")


Output: 

Complete Form

Python3




# Import following modules
from pywebio.input import *
from pywebio.output import *
from pywebio.session import *
import re
  
# For checking Email, whether Valid or not.
regex = '^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$'
  
# For checking Phone Number, whether Valid or 
# not.
Pattern = re.compile("(0/91)?[6-9][0-9]{9}")
  
# For Checking URL, whether valid or not
regex_1 = ("((http|https)://)(www.)?" + 
           "[a-zA-Z0-9@:%._\\+~#?&//=]" +
           "{2,256}\\.[a-z]" +
           "{2,6}\\b([-a-zA-Z0-9@:%" +
           "._\\+~#?&//=]*)")
Pattern_1 = re.compile(regex_1)
  
  
def check_form(data):
    
    # for checking Name
    if data['name'].isdigit():
        return ('name', 'Invalid name!')
        
    # for checking UserName
    if data['username'].isdigit():
        return ('username', 'Invalid username!')
        
    # for checking Age
    if data['age'] <= 0:
        return ('age', 'Invalid age!')
        
    # for checking Email
    if not (re.search(regex, data['email'])):
        return ('email', 'Invalid email!')
      
    # for checking Phone Number
    if not (Pattern.match(str(data['phone']))) 
    or len(str(data['phone'])) != 10:
        return ('phone', 'Invalid phone!')
      
    # for checking Website URL
    if not re.search(Pattern_1, data['website']):
        return ('website', 'Invalid URL!')
        
    # for matching Passwords
    if data['pass'] != data['passes']:
        return ('passes', "Please make sure your passwords match")
  
  
# Taking input from the user
data = input_group("Fill out the form:", [
    input('Username', name='username', type=TEXT,
          required=True, PlaceHolder="@username"),
    
    input('Password', name='pass', type=PASSWORD,
          required=True, PlaceHolder="Password"),
    
    input('Confirm Password', name='passes', type=PASSWORD,
          required=True, PlaceHolder="Confirm Password"),
    
    input('Name', name='name', type=TEXT, required=True
          PlaceHolder="name"),
    
    input('Phone', name='phone', type=NUMBER,
          required=True, PlaceHolder="12345"),
    
    input('Email', name='email', type=TEXT,
          required=True, PlaceHolder="user@gmail.com"),
    
    input('Age', name='age', type=NUMBER, required=True,
          PlaceHolder="age"),
    
    input('Portfolio website', name='website', type=TEXT,
          required=True, PlaceHolder="www.XYZ.com")
    
], validate=check_form, cancelable=True)
  
# Create a radio button
gender = radio("Gender", options=['Male', 'Female'], required=True)
  
# Create a skills markdown
skills = select("Tech Stack", options=[
  'C Programming', 'Python', 'Web Development', 'Android Development'],
                required=True)
  
# Create a textarea
text = textarea("Comments/Questions", rows=3,
                placeholder="Write something...", required=True)
  
# Create a checkbox
agree = checkbox("Agreement", options=[
    'I agree to terms and conditions'], required=True)
  
# Display output using popup
popup("Your Details",
      f"Username: @{data['username']}\nName: {data['name']}\
      \nPhone: {str(data['phone'])}\nEmail: {data['email']}\
      \nAge: {str(data['age'])}\nWebsite: {data['website']}\
      \nGender: {gender}\nSkill: {skills}\nComments: {text}",
      closable=True)


Output: 



Last Updated : 17 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads