Yogesh Chauhan's Blog

How to Validate User Name, Email Address and URL in PHP?

in PHP on December 14, 2019

We just saw how to get inputs and clean them in following post.

Clean Form Input With These PHP Functions Before Inserting into Database

In this blog post, I'll show you how to force user to enter valid data. For example, user cannot enter numbers in Name field. 

For that I am going to use preg_match function which performs a reg ex match (regular expression match).


preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] );

Simplified Syntax:

preg_match ( pattern to search for , from, store matches-OPTIONAL, flags-OPTIONAL);

As you can see, the first 2 parameters are required in which first one will have the pattern to search for and the second one will have the data in which we are searching the pattern. 

If you pass 3rd parameter, the matched patterns will get stored in an array. 

Read more about this function on official manual of PHP, HERE

Now, lets validate name first.

Validate Name

Assume we are storing the user input of name into the variable $full_name. For example,

$full_name = $_POST["full_name"];

So, the validation will look like this:

if (!preg_match("/^[a-zA-Z ]*$/",$full_name)) {
  $full_name_error = "Please enter letters and white spaces only";

The Reg Ex above will check if the string entered by user has any characters other than letters and numbers. 

The preg_match() will check for letters and white spaces. If that's true the preg_match() will return TRUE and we have ! (negation unary operator) before the preg_match function, which will convert that TRUE into false and the overall IF condition will become false and it won't return any error.

Validate Email

PHP has really cool way to validate email so we don't need to write any more functions and make things complex (you could if you want!)

The function is filter_var() which filters variable with a specified filter.

Simplified Syntax: 

filter_var(variable, filter, options)

We pass the variable and filter to validate email. The second field takes filter and PHP has many filters available. One of them is FILTER_VALIDATE_EMAIL which will check if the entered email is in correct format.

$email = $_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $email_error= "Please enter valid email address";

Assume we are storing the user input for email in to the variable named $email. Now all we need to do is call the function and pass those parameters and values in it.

If the email entered by user is correct then the function will return TRUE and we have the same ! (negation unary operator) before the function, which will convert that TRUE into false and the overall IF condition will become false and it won't return any error.

Validate URL

PHP has function to validate URL as well but I'm going to show you the old way to validate URL as well.

Let's look at the short option first.

$url= $_POST["url"];
if (!filter_var($url, FILTER_VALIDATE_URL)) {
  $url_error= "Please enter valid URL";

It's the same function as email address but with a different filter. 

NOTE: FILTER_VALIDATE_URL is not reliable and it can not validate URLs based on IPv6 addresses.

Let's take a look at the long function.

$url= $_POST["url"];
if (!preg_match("/b(?:(?:https?|ftp)://|www.)[-a-z0-9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]/i",$url)) {
  $url_error= "Please enter valid URL";

This is old and classic way but still effective. It has many different parts to check the url. First it checks for HTTP or FTP (if user has entered in the url). User is not required to enter it but if he / she does that, we need some code to consider that part as valid. 

Then it makes sure the website has www in it immediately followed by a (.) dot. After dot, you can have many possible characters and numbers and all. Then it does make sure that user enters (.) one more time in the url after the domain name. At the end, use will have many possible endings like .com, .ca, .us, .org and all. You can enter anything actually! 

So, this classic way doesn't guaranty that user will enter 100% correct URL but it makes sure that user follows the pattern.

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
WordPress: How to loop through a repeater field in ACF?WordPressHow to use data-* Attributes in HTML?HTMLWordPress: How to loop through ACF group fields?WordPressHow to zoom an element on hover using CSS?CSS@mixin and @include in SCSS (Sass)SCSSCreate dynamic selectors using SCSS (Sass)SCSS