Create New Post

Email Validation using JS Script & PHP Integration

 

To validate an email address using both PHP and JavaScript, you can use the following approach:
 

1. Using JavaScript for Frontend Validation:

<!DOCTYPE html>
<html>
<head>
    <title>Email Validation</title>
    <script>
        function validateEmail() {
            var email = document.getElementById("email").value;
            var regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (regex.test(email)) {
                return true;
            } else {
                alert("Please enter a valid email address");
                return false;
            }
        }
    </script>
</head>
<body>
    <form onsubmit="return validateEmail()">
        <label for="email">Email:</label>
        <input type="text" id="email" name="email">
        <input type="submit" value="Submit">
    </form>
</body>
</html>

 

2. Using PHP for Backend Validation:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST["email"];
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Invalid email format";
    } else {
        echo "Email is valid";
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Email Validation</title>
</head>
<body>
    <form method="post">
        <label for="email">Email:</label>
        <input type="text" id="email" name="email">
        <input type="submit" value="Submit">
    </form>
</body>
</html>
  • In JavaScript, the validateEmail() function is called on form submission. It checks if the entered email matches the regular expression pattern for a valid email address. If not, it displays an alert.
  • In PHP, after the form is submitted, the entered email is retrieved using $_POST and validated using filter_var() with the FILTER_VALIDATE_EMAIL flag. If the email is invalid, an error message is echoed.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

47848