Table of contents
1.
Introduction
2.
Database validators
2.1.
IS_NOT_IN_DB
2.2.
IS_IN_DB
3.
Multiple validators
4.
Custom validators
5.
Validators with dependencies
6.
Other validators
6.1.
CLEANUP
7.
Frequently Asked Questions
7.1.
What are the different types of validators?
7.2.
Does the CLEANUP validator remove whitespaces and unnecessary characters too?
7.3.
Why do we use arguments in validators?
8.
Conclusion
Last Updated: Mar 27, 2024
Medium

Different types of validators in web2py

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Web2py is an open-source, agile development framework for developing web applications. It is written in python with a .py extension. The forms in web2py are used to take inputs from users and perform actions on them by storing the data. The data provided by the users must be validated for security and to ensure it is not breached or mishandled. We have validators to handle this validation in web2py. Validators are the classes that are used to validate input fields and provide security to the data. Let’s learn about various validators in web2py in this article.

form validation image

Database validators

The database validators are used to monitor the data in the database tables. They check whether the data exists in the database are not. Let’s learn the database article with examples.

IS_NOT_IN_DB

This validator checks whether the data or an element is not present in the database. Whenever we try inserting any element into the database, we must check if it already exists to avoid duplicate values. 

db.define_table('person', Field(personName, unique=True))
db.person.personName.requires = IS_NOT_IN_DB(dbset, field, error_message='The name already exists in database', allowed_override=[])
You can also try this code with Online Python Compiler
Run Code
screenshot of database validation

dbset: a collection of all the entities to search the name from

Field: contains the name of the person

error_message: displays an error message when the validation fails

allowed_override: defines whether you can override a value in the database

In the above code, the validator checks if the element or person already exists in the database when we try to insert the value.

IS_IN_DB

This validator checks whether the data or an element is present in the database. Whenever we try inserting any element into the database, we must check if it already exists to avoid duplicate values.

db.define_table('person', Field(personName, unique=True))
db.owner.requires = IS_IN_DB(db, 'person.id', 'db.person.personName, error_message=’The name doesn't exist in database’))
You can also try this code with Online Python Compiler
Run Code
screenshot of database validation

The above code checks whether the person with the id person.id and name is in the database. If the name is not in the database, it displays a message: "The name doesn't exist in database”.

Multiple validators

The multiple validators are used when we want to validate and do multiple validations on a single value. The output of a validator is passed on to the next validator as input. If any of the validators fail, all the other validators will also fail, displaying an error message.

Custom validators

We can create custom validators and make them act similarly to pre-defined ones. We can call the validators and return the value we want when the validation is successful. If not, we can display the error message.

def valid(str):
	if (type)str == string:
		return 1
	return 0
	
str = “coding ninjas - validators”
if valid(s):
	print(“valid”)
else:
	error_message = “invalid”
	print(error_message)
You can also try this code with Online Python Compiler
Run Code
screenshot of custom validation

The above code validates when the given input is a string and prints ”valid” or displays an error message “invalid”.

Validators with dependencies

There are few cases when the result of the validator may depend on another validator. If we consider a registration form an example, we retype our password to confirm it. But if we leave the password field empty in the first field, we cannot validate if the password re-entered by the user is equal to the first one.  

def index():
    form = SQLFORM.factory(
        Field('username', requires=IS_NOT_EMPTY()),
        Field('password', requires=IS_NOT_EMPTY()),
        Field('password_again',
              requires=IS_EQUAL_TO(request.vars.password, error_message=”passwords are not matched”)))
You can also try this code with Online Python Compiler
Run Code


In the above code, we take the username and password values from the user and store them in the database. When we enter a password, the validator checks if the password is empty and validates if the password re-entered by the user is the same as the one entered before. If both the passwords are not matched, an error message is displayed, as shown below.

screenshot of password validation

Other validators

We also have other validators that do not come under the categories mentioned above. Let’s discuss a validator CLEANUP in this section.

CLEANUP

This validator is more like a filter, so this never fails. We don’t use the error_message argument in this validator, as we don’t have a case of validation failure. This validator can be used by passing a regular expression to it. If not by default, it will remove all the characters from the expression whose ASCII values are not in the list [10, 13, 32-127]. 

CLEANUP('[^\d]')('Hello 123 world 456')
You can also try this code with Online Python Compiler
Run Code


The d in the above code represents digits, and all the characters that are not digits are removed from the above regular expression, and the output will be “123456”.

Frequently Asked Questions

What are the different types of validators?

There are different types of validators provided by web2py. They are; security, complexity, special type, text, date and time, range, set and equity, database, custom, multiple, and dependency validators. 

Does the CLEANUP validator remove whitespaces and unnecessary characters too?

The CLEANUP validator performs the initial strip and removes the leading(beginning of the line) and trailing(end of the line) whitespaces in a regular expression.

Why do we use arguments in validators?

We use arguments in validators to provide extra information and conditions to perform the validation. For example, we check if a name is alphanumeric using the IS_ALPHANUMERIC validator, to which we can add an error_message argument to display an error in case of validation failure.

Conclusion

We have discussed the concept of different types of validators in web2py in this article. You can now start coding in your preferred language.

Check out this problem - Duplicate Subtree In Binary Tree

Hey Ninjas! We hope this blog helped you better to understand the validators in the web2py. Please check out Coding Ninjas for more unique courses and guided paths. Also, try Coding Ninjas Studio for more exciting articles, interview experiences, and fantastic Data Structures and Algorithms problems. Please upvote our blog to help the other ninjas grow.

Happy Coding!

Thank you by coding ninjas
Live masterclass