-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidation.php
More file actions
59 lines (50 loc) · 1.5 KB
/
validation.php
File metadata and controls
59 lines (50 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<!DOCTYPE html>
<html>
<head>
<title>Form Validation in PHP</title>
</head>
<body>
<h2>PHP Form Validation Example</h2>
<form method="post" action="">
Name: <input type="text" name="name"><br><br>
Email: <input type="text" name="email"><br><br>
Age: <input type="text" name="age"><br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if (isset($_POST['submit'])) {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$age = trim($_POST['age']);
$errors = [];
// Check empty fields
if (empty($name) || empty($email) || empty($age)) {
$errors[] = "All fields are required.";
}
// Validate name length
if (!empty($name) && strlen($name) < 3) {
$errors[] = "Name must be at least 3 characters long.";
}
// Validate email format
if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format.";
}
// Validate age as numeric
if (!empty($age) && !is_numeric($age)) {
$errors[] = "Age must be a number.";
}
// Display results
if (empty($errors)) {
echo "<h3 style='color:green;'>Form submitted successfully!</h3>";
echo "Name: $name <br>Email: $email <br>Age: $age";
} else {
echo "<h3 style='color:red;'>Errors:</h3><ul>";
foreach ($errors as $error) {
echo "<li>$error</li>";
}
echo "</ul>";
}
}
?>
</body>
</html>