Created
January 13, 2026 02:52
-
-
Save maxixo/34c4436d48b712cf96aa6d48c84102d4 to your computer and use it in GitHub Desktop.
Basic form validation in php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <meta charset="utf-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1"> | |
| <title>Form Validation</title> | |
| </head> | |
| <body> | |
| <?php | |
| $name = $email = $age = ""; | |
| $nameErr = $emailErr = $ageErr = ""; | |
| if ($_SERVER['REQUEST_METHOD'] == "POST") { | |
| if (empty($_POST["name"])) { | |
| $nameErr = "Name is required"; | |
| } else { | |
| $name = test_input($_POST['name']); | |
| if (!preg_match("/^[a-zA-Z-' ]*$/", $name)) { | |
| $nameErr = "Only letters and white space allowed"; | |
| } | |
| } | |
| if (empty($_POST['email'])) { | |
| $emailErr = "Email is required"; | |
| } else { | |
| $email = test_input($_POST["email"]); | |
| if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { | |
| $emailErr = "Invalid email format"; | |
| } | |
| } | |
| if (empty($_POST["age"])) { | |
| $ageErr = "Age is required"; | |
| } else { | |
| $age = test_input($_POST["age"]); | |
| if (!filter_var($age, FILTER_VALIDATE_INT)) { | |
| $ageErr = "Age must be a number"; | |
| } | |
| } | |
| } | |
| function test_input($data) { | |
| $data = trim($data); | |
| $data = stripslashes($data); | |
| $data = htmlspecialchars($data); | |
| return $data; | |
| } | |
| ?> | |
| <h2>Registration Form</h2> | |
| <form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>"> | |
| 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> | |
| Age: <input type="text" name="age" value="<?php echo $age; ?>"> | |
| <span style="color:red;"><?php echo $ageErr;?></span><br><br> | |
| <input type="submit" value="Submit"> | |
| </form> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment