PHP form validation helps maintain data integrity and security, preventing SQL injection, XSS, and other malicious attacks.
From the user input perspective, it prevents issues such as storing incorrect or incomplete data in the database. Plus, users can get immediate feedback about the input’s correctness, which improves their experience with your product.
In this article, we’ll cover different types of validation for a simple registration form, starting with a quick overview of the available options.
There are a few options to validate a PHP form – you can use a PHP script, Ajax, JS, or a database.
I’ll briefly cover the benefits and challenges of each. Then, we’ll move to integration tutorials, including exemplary scripts.
Benefits:
Challenges:
Benefits:
Challenges:
Benefits:
Challenges:
Benefits:
Challenges:
Note that the choice of method depends on the project’s specific needs, the resources available, and the development team’s expertise.
Also, it’s important to implement multiple validation layers:
By combining these layers and incorporating sanitization practices, you can build robust and secure forms that enhance your application’s functionality and user experience. Additionally, consider exploring server-side validation libraries for streamlined implementation and advanced features.
I’ll start with a basic PHP validation script as it’s one of the quickest methods to implement.
In this PHP tutorial, I won’t be adding any CSS to the HTML entities as the main focus is on the email form validation.
Design your form with the necessary fields and include a submit button.
<form method="post" action="validate.php">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
<input type="submit" name="submit" value="Submit">
</form>
Copy
At the beginning of your PHP script, sanitize and validate the input. Use the $_POST
superglobal array to access the input field form data.
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Sanitize and validate name
$name = test_input($_POST["name"]);
$nameErr = "";
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
// Sanitize and validate email
$email = test_input($_POST["email"]);
$emailErr = "";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
// ... Additional validation checks ...
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
If there are validation errors, display them to the user. Otherwise, proceed with the form processing.
if ($nameErr != "" || $emailErr != "") {
echo "<b>Error:</b>";
echo "<br>" . $nameErr;
echo "<br>" . $emailErr;
} else {
// Process the form data
echo "Form submitted successfully";
}
php echo htmlspecialchars
function. It also makes the validation compatible with different encodings like UTF-8. Here’s the exemplary snippet:$userInput = "<script>alert('Hello!');</script>";
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
class FormValidator {
private $data;
private $requiredFields = [];
public function __construct($postData) {
$this->data = $postData;
}
public function validate() {
// Common validation rules
$this->validateRequiredFields();
$this->validateEmailFormat();
// Add more validation methods as needed
}
private function validateRequiredFields() {
// Check if required fields are present
foreach ($this->requiredFields as $field) {
if (empty($this->data[$field])) {
throw new Exception("{$field} is required.");
}
}
}
private function validateEmailFormat() {
// Check if email field is in a valid format
if (!filter_var($this->data['email'], FILTER_VALIDATE_EMAIL)) {
throw new Exception("Invalid email format.");
}
}
// Define other validation methods...
}
// Usage
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$validator = new FormValidator($_POST);
try {
$validator->validate();
// If validation passes, process the form
} catch (Exception $e) {
echo $e->getMessage();
}
}
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Radio button validation
if (!isset($_POST['gender']) || empty($_POST['gender'])) {
echo "Gender selection is required.<br>";
} else {
$gender = $_POST['gender'];
// You can add additional validation here if needed
}
// Checkbox validation
if (!isset($_POST['terms']) || $_POST['terms'] !== 'agree') {
echo "You must agree to the terms and conditions.<br>";
} else {
// User agreed to terms and conditions
}
// If no errors, process the form
if (empty($errors)) {
echo "Form submitted successfully.";
}
}
?>
AJAX offers a smooth user experience indeed, but note that you’ll also need to implement server-side CSRF protection. I won’t be covering that in this article.
Start with a simple form in your HTML file with the action
set to a PHP script and the method
set to POST
.
<form id="contactForm" action="process.php" method="post">
Name: <input type="text" name="name" required><br>
Email: <input type="email" name="email" required><br>
Message: <textarea name="message" required></textarea><br>
<input type="submit" value="Submit">
</form>
<div id="response"></div>
Write a native Javascript function that prevents the default form submission and sends the form data via AJAX to the server.
const form = document.getElementById('contactForm');
form.addEventListener('submit', function(event) {
event.preventDefault();
const formData = new FormData(form);
fetch(form.action, {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
document.getElementById('response').innerHTML = data;
})
.catch(error => {
console.error('Error:', error);
});
});
Create a process.php
file to handle the form submission. Use PHP’s built-in functions like filter_var()
to check for valid email address and trim()
to remove extra spaces.
<?php
$name = trim(filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING));
$email = trim(filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL));
$message = trim(filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
} else {
// Process the form data (using prepared statements for database interaction)
echo "Form submitted successfully";
}
?>
Similar to AJAX, JS is great for improved user experience, but you’ll still need to make sure the method can’t be manipulated. So it’s wise to implement server-side validation as well.
Similar to the AJAX example, create a form in your HTML file.
<form id="contactForm" action="process.php" method="post">
<!-- form fields -->
<input type="submit" value="Submit">
</form>
<div id="error"></div>
Add a JavaScript function to validate the form fields before submission.
function validateForm() {
var email = document.forms["contactForm"]["email"].value;
var errorDiv = document.getElementById("error");
if (!validateEmail(email)) {
errorDiv.innerHTML = "Invalid email format";
return false;
} else {
errorDiv.innerHTML = "";
return true;
}
}
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
Ensure that you also validate the data on the server side using PHP, as client-side validation can be bypassed. And make sure your PHP file is properly protected.
Important Note:
The validation script contains a mile-long regex. It works, but it’s not exactly an example of best coding practice, and in a real-world scenario, you’d want to use a JS validation library to avoid false positives or negatives. Here’s an example with the email-validator
lib:
// Import the email-validator library
var validator = require('email-validator');
function validateForm() {
var email = document.forms["contactForm"]["email"].value;
var errorDiv = document.getElementById("error");
if (!validator.validate(email)) {
errorDiv.innerHTML = "Invalid email format";
return false;
} else {
errorDiv.innerHTML = "";
return true;
}
}
Aside from what’s already covered, which is mostly email and name validation. There are several other form elements you may want to validate. Also, it’s advisable to include CAPTCHA with your forms to ward off bots.
The quick tutorials below include CAPTCHA integration, empty field, phone number, and website validation. Depending on your specific use case, and the form you created, you probably won’t need all.
As indicated, CAPTCHAs are used to verify that the user is human and not a bot. They typically involve solving a puzzle or identifying objects in images. Here’s how to integrate it.
Thank you for your interest! To access the full article "How to Set Up PHP Form Validation," please visit the original published post on Mailtrap's website.