Loading...

Form Validation

Basic Example

php
PHP Code
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$errors = [];

// Validate username
if (empty($_POST['username'])) {
$errors['username'] = "Username is required";
} elseif (strlen($_POST['username']) < 5) {
$errors['username'] = "Username must be at least 5 characters long";
}

// Validate email
if (empty($_POST['email'])) {
$errors['email'] = "Email is required";
} elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors['email'] = "Invalid email format";
}

// Validate password
if (empty($_POST['password'])) {
$errors['password'] = "Password is required";
} elseif (strlen($_POST['password']) < 8) {
$errors['password'] = "Password must be at least 8 characters long";
}

// Output results
if (empty($errors)) {
echo "Form submitted successfully!";
} else {
foreach ($errors as $field => $error) {
echo "$field: $error<br>";
}
}
}
?>

Practical Example

php
PHP Code
<?php
class FormValidator {
private $data;
private $errors = [];

public function __construct($postData) {
$this->data = $postData;
}

public function validateUsername() {
$value = trim($this->data['username'] ?? '');
if (empty($value)) {
$this->errors['username'] = "Username is required";
} elseif (strlen($value) < 5) {
$this->errors['username'] = "Username must be at least 5 characters long";
}
}

public function validateEmail() {
$value = trim($this->data['email'] ?? '');
if (empty($value)) {
$this->errors['email'] = "Email is required";
} elseif (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
$this->errors['email'] = "Invalid email format";
}
}

public function validatePassword() {
$value = $this->data['password'] ?? '';
if (empty($value)) {
$this->errors['password'] = "Password is required";
} elseif (strlen($value) < 8) {
$this->errors['password'] = "Password must be at least 8 characters long";
}
}

public function validateForm() {
$this->validateUsername();
$this->validateEmail();
$this->validatePassword();
return $this->errors;
}
}

// Using the class to validate form
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$validator = new FormValidator($_POST);
$errors = $validator->validateForm();

if (empty($errors)) {
echo "Form submitted successfully!";
} else {
foreach ($errors as $field => $error) {
echo "$field: $error<br>";
}
}
}
?>

📊 Reference Table

PHP Element/Concept Description Usage Example

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

4
Questions
🎯
70%
To Pass
♾️
Time
🔄
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top