DEV Community

Cover image for Validation mask through Regex with Python
Rafael Rocha
Rafael Rocha

Posted on • Updated on

Validation mask through Regex with Python

Introduction

Regular expressions (or Regex) is a robust approach used to analyze whether a string belongs to a certain language, and is used in the validation of several fields, such as email and password, as will be seen here. The library re of Python was used to validate each field.

The regex is a composition of symbols, characters with special functions, what, grouped among themselves and with literal characters form a regex. The regex is interpreted as a rule witch will indicate success if it matches all of his conditions.

To build the validations masks of email and password is considerate the following alphabets: Σ = {a, b, c, …, z}, Γ = {A, B, C, …, Z} and N = {0, 1, 2, …, 9}.

Validation Masks

The strings accepted by the email field have symbols from Σ and must contain a symbol @ and end with .br, where it must have at least one symbol Σ between @ and .br. Furthermore, the email must start with the @ symbol.

The password field may contain symbols of all alphabets Σ, Γ and N. It is necessary at least one symbol of Σ and N. Besides, the password must contain, necessarily, length of 8.
The regex to validation mask of email is given as following:

^[a-z]+@[a-z]+.br$
Enter fullscreen mode Exit fullscreen mode

This expression accepts at least one symbol of Σ, where the character ^ indicates that start with symbols from a to z ([a-z]), the character + ensures at least one symbol of Σ, and $ ensures that string is finished with .br.

The password regex is showed bellow:

(?=.*\d)(?=.*[A-Z])[a-zA-Z0-9]{8}$
Enter fullscreen mode Exit fullscreen mode

The expression (?=.\d) ensures at least one symbol of **N. In the same way, the expression (?=.[A-Z]) ensures at least one symbol of Γ. Besides, the two first expressions indicate that no matter where symbols of N and Γ appear in the password. Lastly, the expression [a-zA-Z0–9]{8} ensures symbols of all alphabets, and the string must have exactly a length of 8.

Example

The function match of re python library is used to test the regex of each field. The first argument of function match is the regex created, and the second is the string to be tested. Bellow is showed the application of re.

import re
regex = '^[a-z]+@[a-z]+.br$'
string = 'whoisgamora@.br'
if bool(re.match(regex, string)):
    print('Valid email!')
else:
    print('Invalid email!')
Enter fullscreen mode Exit fullscreen mode

This example generates the message Invalid email!, because there isn’t any symbol of Σ between @ and .br.


A complete application of the validation mask through regex can be tested in Colab. Other fields were tested in the Colab, as name and last name, and telephone number.

Top comments (0)