When designing a website, validation forms are one of the aspects that need to be paid close attention to. This process helps you review the user's input data and ensure its accuracy and correctness. Validation forms usually involve checking fields to ensure that users have entered all necessary information and that specific formats, such as email or phone number, are adhered to.
In PHP, validation forms can be performed in two ways: client-side validation using JavaScript, and server-side validation using PHP. Server-side validation is done through PHP and, by reviewing data on the server, is more secure compared to validation done on the client-side through JavaScript.
Common processes in validation forms can include preventing the entry of empty fields, ensuring compliance with the entered data formats, and checking the length of input fields. One of the very common cases is that the user must verify the structural correctness in order to send data or access more important features.
Now, I would like to show you a simple example of a registration form in PHP to get you more familiar with how validation of user input data works using PHP. This example includes fields for name, email, and a message that each one of these fields must be validated.
Validation forms help users reduce common mistakes in forms, allowing for data to be recorded faster and more accurately. Additionally, it prevents developers from encountering bugs and errors in program integration.
<?php
// define variables and set to empty values
$name = $email = $message = "";
$nameErr = $emailErr = $messageErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$messageErr = "Message is required";
} else {
$message = test_input($_POST["message"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
: Indicates the start of a PHP script.
$name = $email = $message = "";
: Defines variables to store input data and initialize them as empty.
if ($_SERVER["REQUEST_METHOD"] == "POST")
: Checks whether the form has been submitted or not.
empty($_POST["name"])
: Checks if the name field is empty.
test_input()
: A function used to sanitize input data for increased security.
filter_var($email, FILTER_VALIDATE_EMAIL)
: Uses a PHP filter for validating emails.