Simple Contact Form Validation Using PHP

phpforloopPHP is a server side scripting language that is used by web developers to build dynamic websites or web-based applications. The term “dynamic websites” means that the websites provides functionality you use to store, retrieve, update or delete information in a database. PHP is embedded in HTML (Hypertext up Language), which is a markup language used to make static web pages. HTML is written in tags enclosed in the angular brackets like <html>, <body> etc. The web browser reads HTML documents and displays the result. PHP is also a markup language and is used in combination with HTML, which makes web applications and websites more interactive and efficient.

The PHP processor module interprets a PHP script at the server level and returns the generated web page. PHP code is written within PHP tags and can be embedded inside the HTML file or used separately. PHP is a high level programming language that supports object oriented programming concepts, which is the biggest advantage. This makes PHP very secure and reliable for transactions and sending highly confidential data over the web. The best advantage of using PHP among other server-side scripting languages is that it is open-source, which means that you don’t have to pay money to use it.

Learn PHP from scratch by watching a tutorial at Udemy.com

PHP is enclosed within tags specified in the following code:

<?php
echo '<p>Hello I am PHP</p>';
?>

What is Validation?

The term “validation” means to check input submitted by the user. The form is the input text boxes, radio boxes, check boxes and other web controls used to collect data. Validation is performed after the client enters all the required data and presses the “Submit” button. If any of the data entered does not match a required pattern, it’s missing or it’s wrongly entered, the information is not stored and returned back with an error message. The user will then have to edit the input before re-submission.

There are 2 types of Validation:

Client-Side Validation: In client-side validation, validation is performed on the web browser on the client machine. This is possible by using JavaScript.

Server Side Validation: In server-side validation, the data is sent to the server when the submit button is pressed. Server-side validation is much more reliable and secure compared to client side validation. All server side scripting languages such as PHP perform this type of validation.

Making a Simple Contact Form in HTML

<html>

<head>

<title>Validation Form</title>

</head>

<body>

<form id="contact_form" method="post" action="."> <br />

Label <input type="text" name="name" class="textfield" value="" /> <br />

Email <input type="text" name="email" class="textfield" value="" /> <br />

Phone Number <input type="text" name="number" class="textfield" value="" /> <br />

<p><input type="submit" name="submit" class="button" value="Submit" /></p>

</form>

</body>

</html>

In the above contact form, we have three input fields named name, email and phone number. All the input fields are placed inside the form tag. The input tag has the attribute “type,” which defines the type of input field such as a text field, password or button.

Want to learn more about PHP? Check out a tutorial at Udemy.com

The form tag has an attribute named “method,” which defines how the data entered by the user is submitted on the server. Generally, there are two ways to submit data to the server: POST and GET. GET passes the value to the server through the url in querystring variables while POST sends the data in an enclosed message body.

Let’s add some PHP code to the contact form page so that the data is sent to the server for validation.

<?php

if(isset($_POST['submit'])) {

//include validation class

//assign post data to variables

$name = trim($_POST['name']); // Storing username

$email = trim($_POST['email']); // Storing email address

$number= trim($_POST['number']); // storing the phone number

}

?>

The above code is executed when the submitted button is clicked. The “isset” function checks whether the value of a variable passed as an argument in the function is set or not and returns “true” or “false”. In the above form “$_POST[‘submit’]” is validated. If the submit button is clicked, then true is returned by the isset function and if not, false is returned. If the value is true, then the “if” block is executed and the  input parameters are saved in the respective variables. The “trim” function is used to remove whitespaces. These variables storing the text field values are then validated.

After you write your code, save the PHP file and name it validate.php. You then include this file in the contact form page using “include” function. Since we already saved all the PHP form’s data, we can run it through the validation script.

To check if any field is left blank, we use the empty function and pass it the arguments.

if(empty($name) && empty($number) && empty($email))

{

echo "All fields are compulsory"

}

If any of the fields are left empty, then an error message is displayed on the screen. The empty function returns true if the variable does not hold any value.

The username can then be checked for various validation points like minimum or maximum length. The code to perform this type of validation is below:

if(strlen($name) >=5 && strlen($name)<=10)

The above code checks whether the username entered has a number of characters that is greater than or equal to 5 and less than or equal to 10. The “strlen”  function returns the number of characters present in the argument passed.

You also need to sometimes check for inappropriate characters. The following code is an example of this type of validation:

if (preg_match("/^[a-z0-9_]+$/i", $name) )

{

return true;

}

else

{

echo "Enter valid username"

}

The preg_match function matches the regular expression passed as an argument. The above regular expression only accepts alphanumeric values with only an underscore as a special symbol. No illegal characters are accepted. Regular expressions are a sequences of characters that are used for pattern  matching with strings.

Validating email: The email field is validated for two things. First, it should not be blank and the entered email must be valid.

<?php

$reg = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';

if (preg_match($reg, $email)) {

echo $email . \" Email Id is accepted.\";

} else {

echo $email . \"Invalid Email ID.\";

}

?>

The above code validates an email address. The regular expression is stored in the variable and passed in the preg_match function to compare the email address value. Email addresses are only accepted if it matches with the regular expression.

Phone number validation:

if((preg_match("/[^0-9]/", '', $str)) && strlen($str) == 10)

{

echo "Invalid phone number

}

Learn how to work more in-depth with PHP at Udemy.com

For valid phone numbers, two conditions are checked: The length of the number should be ten and only numeric values are accepted. The preg_match function matches regular expressions for numeric values and returns true only if numeric values are entered. The “strlen” function checks for the number of characters entered for a phone number, which must be 10 for validation to pass.