Updated On: Tutorial updated and rechecked on 1st of December 2023
Views: 3,155
It is important to validate user input with all your forms in .php. It will ensure that your data remains consistent.
The following .php code displays a simple contact form, but also displays an error message on the same page if the user fails to complete any of the form fields.
There are other ways to validate forms using HTML5, or Javascript, it's all down to personal preference.
Open up your text editor, copy and paste the code below and save the file as form.php then upload it to your local or remote server to test the script.
<?php
if (!$_POST['submit'])
{
form();
} else {
if (empty($_POST['first_name'])) { $error0='<br>First Name'; }
if (empty($_POST['surname'])) { $error1='<br>Surname'; }
if (!filter_var($_POST['email_address'], FILTER_VALIDATE_EMAIL)) { $error2='<br>Valid e-mail address'; }
$error_messages = $error0.$error1.$error2;
if ($error_messages)
{
echo "Please ensure the following fields are completed before submitting your form:<strong>". $error_messages ."</strong><br><br>";
form();
} else {
echo "Thank you for completing the form. Please <a href='form.php'>click here</a> to contine....";
}
}
?>