Advertisement

Google Ad Slot: content-top

PHP Form Validation

~1 min read · PHP
On this page

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 Form Validation

PHP Form Validation Example

Name:

Email:

Gender: > Male > Female

Form Submitted Successfully"; echo "Name: " . $name . "
"; echo "Email: " . $email . "
"; echo "Gender: " . $gender . "
"; } ?>
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: