PHP Form Validation

Form validation is an important part of any web application to ensure that user input is correct and secure. In PHP, form validation can be performed using server-side scripting to check for required fields, proper data formats, and prevent malicious input.


Steps to Validate a Form:


  1. Check if the form is submitted.
  2. Validate required fields.
  3. Validate data format (email, numbers, etc.).
  4. Display error messages.
  5. Retain user input after form submission.


Example of PHP Form Validation
<?php
// Define variables and set empty values
$name = $email = $gender = "";
$nameErr = $emailErr = $genderErr = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate Name
if (!empty($_POST["name"])) {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/", $name)) {
$nameErr = "Only letters and spaces allowed";
}
}

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

// Validate Gender
if (!empty($_POST["gender"])) {
$gender = test_input($_POST["gender"]);
}
}

// Function to sanitize input data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<!DOCTYPE html>
<html>
<head>
<title>PHP Form Validation</title>
</head>
<body>

<h2>PHP Form Validation Example</h2>
<form method="post" action="">
Name: <input type="text" name="name" value="<?php echo $name; ?>">
<span style="color: red;"><?php echo $nameErr; ?></span><br><br>

Email: <input type="text" name="email" value="<?php echo $email; ?>">
<span style="color: red;"><?php echo $emailErr; ?></span><br><br>

Gender:
<input type="radio" name="gender" value="Male" <?php if ($gender == "Male") echo "checked"; ?>> Male
<input type="radio" name="gender" value="Female" <?php if ($gender == "Female") echo "checked"; ?>> Female
<span style="color: red;"><?php echo $genderErr; ?></span><br><br>

<input type="submit" name="submit" value="Submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && $nameErr == "" && $emailErr == "" && $genderErr == "" && !empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["gender"])) {
echo "<h3>Form Submitted Successfully</h3>";
echo "Name: " . $name . "<br>";
echo "Email: " . $email . "<br>";
echo "Gender: " . $gender . "<br>";
}
?>

</body>
</html>

Try it yourself


Explanation:


  1. $_SERVER["REQUEST_METHOD"] == "POST"
  • Checks if the form was submitted via POST method.

   2. Sanitization (test_input())

  • trim() removes extra spaces.
  • stripslashes() removes backslashes.
  • htmlspecialchars() prevents XSS attacks.

3. Validation Logic

  • Name: Ensures it's not empty and only contains letters/spaces.
  • Email: Checks if it's a valid email format.
  • Gender: Ensures a selection is made.

4. Displaying Errors

  • If validation fails, an error message is displayed next to the field.

5. Retaining User Input

  • The value="<?php echo $name; ?>" ensures the input is not lost on form submission.

Output Example:


Before Submission:



After Submission (Invalid Input Example):



After Successful Submission:



Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.