Related post

PHP form validation : How to validate a form in PHP - Zhullyblog





Hello, welcome to zhullyblog. If this is your first time here , please Subscribe to Zhullyblog by Email to get latest tutorial.


PHP form validation



PHP Form Validation: How to validate a form in PHP

In the previous tutorial, we talked about how to access data submitted by user in PHP. In this chapter, we would learn to check or validate input.



What is validation?
When we talk about validation, we are talking about checking whether the user enters an input correctly. Let's take a form for instance. When you create a form, you need user to enter either their name correctly, enter their email correctly, - and the only way to do this is by validating the form. So if the user fails to enter input correctly, the form is redisplayed with an error message.

There are several inputs that you need to validate in a form such as name , Email address etc.
Let's break it down



PHP - Validate name
A name will contain letters and whitespace. The name could be uppercase or lowercase letters. So, if the user fail to enter correctly, it will display an error message.
Here is the code.
statement.




$name =
test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z]*$/",$name)) {
   $nameErr ="Only letters are allowed";
   }



Note: The preg_match( ) function will return true if the input meets the condition and false if it fails to meet the condition.



PHP Validate Email
To validate email ( to check whether the input matches email pattern) , you use the filter_var( ) function. So if the email entered does not meet the requirements, an error message will be displayed.



$email =
test_input($_POST["email"]);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
   $emailErr = "Invalid Email";
   }







PHP Validate Website
Study the code below to check whether the URL has the general URL syntax, (www , https://, etc). If the URL does not match , an error message is displayed.




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



 So, you would have created a form that will take name, Email , website, comment and gender. Then validate the form


Now that we have learnt how to validate each, let's combine them. This is what the code will look like.




<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = test_input($_POST["name"]);
  $email = test_input($_POST["email"]);
  $website = test_input($_POST["website"]);
  $comment = test_input($_POST["comment"]);
  $gender = test_input($_POST["gender"]);
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

    // Check for any possible errors
    if(empty($nameErr) && empty($emailErr) && empty($messageErr)){
        // Recipient email address
        $to = 'recipient@example.com';
     
        // Create email headers
        $headers = 'From: '. $email . "\r\n" .
        'Reply-To: '. $email . "\r\n" .
        'X-Mailer: PHP/' . phpversion();
     
        // Sending email
        if(mail($to, $subject, $message, $headers)){
            echo '<p class="success">Your message has been sent successfully!</p>';
        } else{
            echo '<p class="error">Unable to send email. Please try again!</p>';
        }
    }
}
?>

The code above is the complete code for validation. It will validate the name , website , email of the user.
From the code above, you will see that once the user entries are acceptable and correct, it will send an email to the website admin and display a successful message to the user.

In the next chapter, we would learn to make some field compulsory.


Follow us on

Please share

OTHER TUTORIALS


OTHER TUTORIALS

Get the latest tutorials and updates




Delivered by FeedBurner



Comments