Try Amazon Prime for 30 days

Buy best selling Linux books

<< View More Computer Tips

Added On: 15/12/15   |    Category: PHP5    |    Number of Views: 382

How to validate a form using PHP5   

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(!eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $_POST['email_address'])) { $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....";
}}
?>

<?php
function form()
{
echo "<form method="post" action="">";

echo "First Name: <input type="text" name="first_name" size="35" value="". $_POST['first_name'] . ""><br>";

echo "Surname: <input type="text" name="surname" size="35" value="". $_POST['surname'] . ""><br>";

echo "Email Address: <input type="text" name="email_address" size="35" value="". $_POST['email_address'] . ""><br>";

echo "<input type="submit" name="submit" value="Submit Form">";

echo "</form>";
}

?>

Search

Services

The Linux Foundation

Best selling Unix / Linux books
Nvidia Graphics Cards
Save 15% off .CO.UK domains at 123-Reg
Save 15% off .COM domains at 123-Reg
cPanel Hosting Plans
Xilo Web Hosting Plans