Blog

How to Validate User Properties With Regular Expressions

by on September 12, 2019

 

When working with data, particularly user-submitted data, you often need to validate it. For example, if we are creating a database in which there is a “site” field and corresponding IP address field, it would be very useful to ensure that the data written to these fields is in the appropriate format.

As another example, a table may store data about users, their names, phone number, email address, the website URL from which they came and another password of the specified format. If users enter data that does not meet your expectations and you do not check it properly, then it will be impossible to work with such data.

Fortunately, Backendless provides a convenient tool for managing and setting this restriction for entering data on a specific template. This tool works in concert with the Backendless user registration API.

Data Validation Example

For clarity, let’s check out the scenario described above where we have a table with the following fields: name, phone number, email address, legal address, password.

So here we go, Login to Backendless Console.

Go to the Data section and create a new table called “UsersData”.

Create usersData Table in Backendless Console
Add the fields to our table by going to the SCHEMA tab. Press the create button and a form will pop up. For Name, we will enter the name and for Type, we will leave STRING.

Add Field to Table in Backendless Console

We will repeat the same procedure for all columns (phoneNumber, email, URL, password).

Let’s go back to the DATA BROWSER and create a new record with arbitrary data.

Add Record to Table in the Data Browser

As we see, we can create an object with data that does not meet our expectations.

Let’s fix this situation. To do this, go to the SCHEMA tab again and set the email column VALIDATOR. From the drop-down list, choose “Email address”.

Set Email Address as Field Validator

Accordingly, for phoneNumber we select “US phone number”, for URL we select “URL”, and for name we select “String a-z, A-Z”. We get the following:

Set Data Validators in Backendless Data Browser

Now we used pre-installed validators, but that’s not all the power and usability of using validators in Backendless. We can create our own regular expression for specific tasks to validate input data. For example, let’s say we want 6 to 20 alphanumeric characters in lower and upper case to be written in the password column. To do this, select Custom in the password column validator and enter “[a-zA-Z_0-9] {6,20}”, or a shorter entry “\ w {6,20}” there. (You can create your own RegEx expression using this tool as a reference.)

Now go to the tab, try to enter incorrect data and it will not be allowed. That’s all there is to it.

Happy Coding!

Leave a Reply