Table of contents
1.
Introduction
2.
What are validators?
3.
Text Format Validators
4.
Date and time validators
5.
Range, set, and equality validators.
6.
Complexity and Security Validators
7.
Special type validators
8.
Other validators
9.
Frequently Asked Questions
9.1.
What is IS_JSON validator?
9.2.
What do you mean by SQLFORM.grid and SQLFORM.smartgrid?
9.3.
What is IS_UPLOAD_FILENAME?
9.4.
Is web2py better than Django?
10.
Conclusion
Last Updated: Mar 27, 2024
Medium

What are Validators in web2py

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

Introduction

As we all know, web2py is an open-source web application written in the python programming language, and now we will discuss one of its favorite topics, i.e., validators in web2py. If you go through the web, you will not find more about the validators in web2py as it is a unique topic. But don't worry. In this article, we will discuss the validators in web2py in detail.

Let's start by knowing what the validator is?

Class Image

What are validators?

Validators are nothing but classes that are used to validate input fields, including the forms generated from the database tables. Validators create widgets like drop-down menus and lookups from other tables with the advanced forms derived from SQLFORM. We have already discussed the SQLFORM.smartgrid in web2py; you can check this link.

Let's see some examples of using a validator.

When we use a validator using a FORM field:

INPUT(_name='a', requires=IS_INT_IN_RANGE(0, 10))
You can also try this code with Online Python Compiler
Run Code

 

Method to require a validator for a table field:

db.define_table('student', Field('name'))
db.student.name.requires = IS_NOT_EMPTY()
You can also try this code with Online Python Compiler
Run Code

 

Validators are permanently assigned using the required attribute of a field. Also, a field may have single or multiple validators. 

We can make Multiple validators a part of a list by :

db.student.name.requires = [IS_NOT_EMPTY(), IS_NOT_IN_DB(db, 'student.name')]
You can also try this code with Online Python Compiler
Run Code

 

Commonly validators are called automatically by the function that accepts and processes a FORM that contains a form. Also, they are called in the order in which they are listed.

Text Format Validators

 

IS_ALPHANUMERIC

It checks whether a field value contains an alphabet or a Numeric value.

requires = IS_ALPHANUMERIC(error_message='It must be alphanumeric value')
You can also try this code with Online Python Compiler
Run Code

IS_ALPHANUMERIC Image

IS_UPPER

It is used to convert the value to upper case. It never returns an error.

requires = IS_UPPER()
You can also try this code with Online Python Compiler
Run Code

IS_UPPER Image

IS_LOWER

It is used to convert the value to lowercase. It never returns an error.

requires = IS_LOWER()
You can also try this code with Online Python Compiler
Run Code

 

IS_EMAIL

It checks that the field value looks like an email address or not. It does not try to send an email for confirmation.

requires = IS_EMAIL(error_message='invalid email!')
You can also try this code with Online Python Compiler
Run Code

IS_EMAIL Image

IS_MATCH

It returns an error if a regular expression does not match the value. Otherwise, it does not return an error.

For example - to validate an India zip Code.

requires = IS_MATCH('^\d{8}(-\d{2})?$', error_message='not a zip code')
You can also try this code with Online Python Compiler
Run Code

 

IS_LENGTH

It is used to check if the length of the field's value fits between given boundaries or not? It works for both text and file inputs.

The arguments it can have are the following:

maxsize: It defines maximum allowed length / size (has default = 255)

minsize: It defines the minimum allowed length/size

For example: Check if the text string is shorter than 33 characters or not?

INPUT(_type='text', _name='name', requires=IS_LENGTH(32))
You can also try this code with Online Python Compiler
Run Code

Date and time validators

IS_TIME

This validator is used to check a field value that contains a valid time in the specified format or not.

requires = IS_TIME(error_message='must be in this format HH:MM:SS!')
You can also try this code with Online Python Compiler
Run Code

IS_TIME Image

IS_DATE

It is used to check a field value that contains a valid time in the specified format or not?

requires = IS_DATE(format=T('%Y-%m-%d'), error_message='must be in YYYY-MM-DD! format')
You can also try this code with Online Python Compiler
Run Code

IS_DATE Image

IS_DATETIME

It is used to check a field value that contains a valid datetime in the specified format or not.

requires = IS_DATETIME(format=T('%Y-%M-%D %H:%M:%S'), error_message='must be in YYYY-MM-DD HH:MM: SS! format')
You can also try this code with Online Python Compiler
Run Code

 

IS_DATETIME Image

IS_DATE_IN_RANGE

This validator works very much like the previous validator, but it allows to specify a range in date:

requires = IS_DATE_IN_RANGE(format=T('%Y-%m-%d'),
                   minimum=datetime.date(2022, 1, 1),
                   maximum=datetime.date(2022, 12, 31),
                   error_message='must be YYYY-MM-DD!')
You can also try this code with Online Python Compiler
Run Code

 

IS_DATETIME_IN_RANGE

It also works similar to the previous validator, but it allows to specify a range in date:

requires = IS_DATETIME_IN_RANGE(format=T('%Y-%M-%D %H:%M:%S'),
                       minimum=datetime.datetime(2022, 1, 1, 10, 30),
                       maximum=datetime.datetime(2022, 12, 31, 8, 45),
                       error_message='must be YYYY-MM-DD HH: MM::SS!')
You can also try this code with Online Python Compiler
Run Code

 

Range, set, and equality validators.

Range Image

IS_EQUAL_TO

It checks whether the validated value is equal to a given value or not. 

requires = IS_EQUAL_TO(request.vars.password, error_message='password not match')

IS_EQUAL_TO Image

IS_NOT_EMPTY

It checks that the content of the field value will not be None, empty string, or an empty list.

requires = IS_NOT_EMPTY(error_message='not be empty!')
You can also try this code with Online Python Compiler
Run Code

 

IS_NULL_OR

Deprecated, an alias for IS_EMPTY_OR.

 

IS_EMPTY_OR

This validator allows empty values on a field and other requirements according to our needs. 

Let's take an example where a field may be a date, but it can also be empty. 

IS_EMPTY_OR validator allows this:

requires = IS_EMPTY_OR(IS_DATE())
You can also try this code with Online Python Compiler
Run Code

 

IS_EXPR

This validator lets us express a general condition using a callable that takes a value to validate and returns the None or error message to accept the input values.

requires = IS_EXPR(lambda l: T('not divisible by 5') if int(l) % 5 else None)
You can also try this code with Online Python Compiler
Run Code

 

IS_DECIMAL_IN_RANGE

This validator converts the input into a Python Decimal. Python Decimal arithmetic is used for comparison which generates an error if the decimal does not fall within the specified inclusive range. 

The minimum and the maximum limits can be None, which means no lower or upper limits. Also, the dot argument is optional that allows us to internationalize the symbol that is used to separate the decimals.

INPUT(_type='text', _name='python', requires=IS_DECIMAL_IN_RANGE(0, 10, dot="."))
You can also try this code with Online Python Compiler
Run Code



IS_FLOAT_IN_RANGE

It checks whether the field value is a floating point number or not. The number also has to lie within a definite range.

For example, The value is between the range 0<value<101.

requires = IS_FLOAT_IN_RANGE(0, 101, dot=".", error_message='not in range')
You can also try this code with Online Python Compiler
Run Code

 

IS_INT_IN_RANGE

It checks whether the field value is an integer number or not within a specified range.

Lets take an example where value, 0 <= value < 99:

requires = IS_INT_IN_RANGE(0, 99, error_message='not in range!')
You can also try this code with Online Python Compiler
Run Code

 

IS_IN_SET

In SQLFORM (and the grids) in web2py, this validator is used where we want to set the form field to an optional field (i.e., with a drop-down menu) automatically.

IS_IN_SET checks whether the field values are in a set or not.

requires = IS_IN_SET(['x', 'y', 'y'], zero=T('choose one'),error_message='must be x or y or z)
You can also try this code with Online Python Compiler
Run Code

 

Complexity and Security Validators

IS_STRONG

This validator enforces the complexity requirements of a field. It usually takes a password field.

IS_STRONG Image

For example-

requires = IS_STRONG(min=10, special=1, upper=1)
You can also try this code with Online Python Compiler
Run Code

where:

  • min- It is the minimum length of the value.
  • special- It is the minimum number of required special characters; by default, It can be any of the following ~!!@#$%^&*()_+-=?<>,.:;{}[]| .
  • upper- It is the minimum no. of upper case characters.

The other accepted arguments are the following:

  • invalid- It is the list of forbidden characters. By default invalid=' "'
  • max- It is the maximum length of the value.
  • lower- It is for the minimum number of lowercase characters.

 

We can provide an error_message for any other validator, although IS_STRONG is very much clever to offer a clear message describing the validation failure.

We can use is entropy as an argument where entropy is a minimum value for the complexity of the value to accept (a number).

IS_STRONG(entropy=100.0)('hello') ('hello', Entropy (25.63) less than required (100.0))
You can also try this code with Online Python Compiler
Run Code

 

Python Image

Special type validators

IS_LIST_OF

This validator helps us to ensure length limits on the values of the type list. We can use minimum, maximum, and error_message arguments for this purpose.

For example:

requires = IS_LIST_OF(minimum=2)
You can also try this code with Online Python Compiler
Run Code

 

IS_LIST_OF_EMAILS

This is a specially designed validator that works with the following field:

Field('email', 'list:string',
      widget=SQLFORM.widgets.text.widget,
      requires=IS_LIST_OF_EMAILS(),
      filter_in=lambda u: \
          IS_LIST_OF_EMAILS.split_email.findall(u[0]) if u else u,
      represent=lambda v, r: \
          XML(', '.join([A(x, _href='mailto:'+x).xml() for x in (v or [])]))
     )
You can also try this code with Online Python Compiler
Run Code

 

ANY_OF

This validator acts like a logical OR for a given validator. It takes a list of validators as input and accepts a value if any of them do.

requires = ANY_OF([IS_ALPHANUMERIC(), IS_EMAIL()])
You can also try this code with Online Python Compiler
Run Code

 

IS_IMAGE

It checks if a file uploaded through the file input was saved in one of the selected image formats and had dimensions within given limits.

IS_IMAGE Image

This validator did not check for maximum file size. We have to use IS_LENGTH for that. It would return a validation failure if no data were uploaded. It supports BMP, GIF, JPEG, and PNG file formats and does not require the Python Imaging Library.

Following are the arguments that it takes:

  • extensions: This iterable contains allowed image file extensions in lowercase.
  • maxsize: This iterable has the maximum width and height of the image.
  • minsize: This includes the minimum width and height of the image.

We must use (-1, -1) as minsize to bypass the image-size check.

Some examples are:

Check if the uploaded file is in any of the supported image formats:

requires = IS_IMAGE()
You can also try this code with Online Python Compiler
Run Code

 

Check if the uploaded file is either JPEG or PNG:

requires = IS_IMAGE(extensions=('jpeg', 'png'))
You can also try this code with Online Python Compiler
Run Code

 

IS_FILE

Check if the name and extension of a file uploaded through file input match the criteria.

INPUT(_type='file', _name='python', requires=IS_FILE(extension='pdf'))
You can also try this code with Online Python Compiler
Run Code

 

It check if a file is called 'codingninjas' and has a jpg or png extension or not:

INPUT(_type='file', _name='python', requires=IS_FILE(filename='codingninjas', extension=['jpg', 'png']))
You can also try this code with Online Python Compiler
Run Code

 

IS_IPV4

IS_IPV4 Image

It checks if a field's value is an IP version 4 address in decimal form. It can be set to force addresses from a particular range.

The signature for the IS_IPV4 constructor is-

IS_IPV4(minip='0.0.0.0', maxip='255.255.255.255', invert=False, is_localhost=None, is_private=None, is_automatic=None, error_message='Enter the valid IPv4 address')
You can also try this code with Online Python Compiler
Run Code

Where:

  • minip- It is the lowest allowed address
  • maxip- It is the highest permitted address
  • Invert is a flag to reverse the allowed address range, i.e., if set to True will enable addresses only from outside of the given range.

We can pass the IP address either as a string or as a list or tuple of 4 integers. (e.g. '192.168.0.1') or (e.g. [192, 168, 0, 1]).

For example-

To allow only addresses between '192.165.20.01' and '192.165.20.20' or between '192.165.30.100' and '192.165.30.200', we can use:

requires = IS_IPV4(minip=('192.165.20.01', '192.165.30.100'), maxip=('192.165.20.20', '192.165.30.200'))
You can also try this code with Online Python Compiler
Run Code

Examples:

Check for a valid IPv4 address:

requires = IS_IPV4()
You can also try this code with Online Python Compiler
Run Code


Check for a valid private network IPv4 address:

requires = IS_IPV4(minip='192.165.0.1', maxip='192.165.255.255')
You can also try this code with Online Python Compiler
Run Code

 

IS_IPV6

IS_IPV6 Image

It checks if a field's value is an IP version 6 address in hexadecimal form.

The signature for the IS_IPV6 constructor is-

IS_IPV6(is_private=None, is_link_local=None, is_reserved=None, is_multicast=None, is_routeable=None, is_6to4=None, is_teredo=None, subnets=None, error_message='Enter the valid IPv6 address')
You can also try this code with Online Python Compiler
Run Code

Examples:

Check for a valid IPv6 address:

requires = IS_IPV6()
You can also try this code with Online Python Compiler
Run Code

Check for a valid private network IPv6 address:

requires = IS_IPV6(is_link_local=True)
You can also try this code with Online Python Compiler
Run Code

 

IS_IPADDRESS

It checks if a field's value is an IP address or not? (either version 4 or version 6). Checks are done using the appropriate. 

For IS_IPV4 and IS_IPV6 validators, the arguments which are only added are the following-

  • is_ipv4, set to True to move version 4 or set to False to forbid version 4
  • is_ipv6, set to True to move version 6 or set to False to ban version 6

 

Examples:

Check for a valid IP address (both IPv4 and IPv6):

requires = IS_IPADDRESS()
You can also try this code with Online Python Compiler
Run Code

Check for a valid IP address (IPv6 only):

requires = IS_IPADDRESS(is_ipv6=True)
You can also try this code with Online Python Compiler
Run Code

Other validators

CLEANUP

This is a filter. It never fails. It removes all characters whose decimal ASCII codes are not in the list [10, 13, 32-127]. It always performs an initial strip on the value.

requires = CLEANUP()
You can also try this code with Online Python Compiler
Run Code

We can pass a regular expression to decide what has to be removed; for example, to clear all non-digit characters, use:

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

THE END Image

Frequently Asked Questions

What is IS_JSON validator?

It checks whether a field value is in JSON format or not.

And If native_json is set to False by default then it converts the input value to the serialized value otherwise the input value remains unchanged.

What do you mean by SQLFORM.grid and SQLFORM.smartgrid?

Both high-level objects create complex CRUD (Create, Read, Update, Delete) controls.

What is IS_UPLOAD_FILENAME?

This is the older version of IS_FILE that is used to check the files whether the name and extension of a file uploaded through the file input match the criteria or not.

Is web2py better than Django?

web2py differs from Django because it is more compact, easier to learn, and has no project-level configuration files. Its syntax is much cleaner than the PHP-based frameworks.

Conclusion

We have discussed the validators and their types in web2py. We have also discussed their examples and last some FAQs. 

After reading about the validators in web2py, are you not feeling excited to read/explore more articles on Data Structures and Algorithms? Don't worry; Coding Ninjas has you covered. See web2pyWhat is web2pyweb2py Introductionweb2py Installation, and Creating a New Web2Py Application to learn.

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass