Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Form Validation Using Regular Expressions</title>
- </head>
- <body>
- <h2>Registration Form</h2>
- <form method="POST" action="">
- <label for="email">Email:</label><br>
- <input type="email" id="email" name="email"
- value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>" required><br><br>
- <label for="username">Username (5-15 characters, letters, and numbers only):</label><br>
- <input type="text" id="username" name="username"
- value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>"
- required><br><br>
- <label for="password">Password (min 8 characters, at least one letter and one number):</label><br>
- <input type="password" id="password" name="password"
- value="<?php echo isset($_POST['password']) ? htmlspecialchars($_POST['password']) : ''; ?>"
- required><br><br>
- <input type="submit" name="submit" value="Submit">
- </form>
- <?php
- // Run the validation logic only after the form is submitted
- if ($_SERVER["REQUEST_METHOD"] == "POST") {
- // Get user inputs from form submission
- $email = $_POST['email'];
- $username = $_POST['username'];
- $password = $_POST['password'];
- // Function to validate email using regex
- function validateEmail($email)
- {
- return preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email);
- }
- // Function to validate username using regex
- function validateUsername($username)
- {
- return preg_match("/^[a-zA-Z0-9]{5,15}$/", $username);
- }
- // Function to validate password using regex
- function validatePassword($password)
- {
- return preg_match("/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/", $password);
- }// Validate the inputs
- $isEmailValid = validateEmail($email);
- $isUsernameValid = validateUsername($username);
- $isPasswordValid = validatePassword($password);
- // Output validation results after form submission
- echo "<h3>Validation Results:</h3>";
- echo "Email validation: " . ($isEmailValid ? "Valid" : "Invalid") . "<br>";
- echo "Username validation: " . ($isUsernameValid ? "Valid" : "Invalid") . "<br>";
- echo "Password validation: " . ($isPasswordValid ? "Valid" : "Invalid") . "<br>";
- }
- ?>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement