Mail id validation along with example

Here's an example of a login form with email validation using JavaScript:

html
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
<script>
function validateForm() {
    var email = document.forms["loginForm"]["email"].value;
    var password = document.forms["loginForm"]["password"].value;

    // Email validation using regular expression
    var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
        alert("Please enter a valid email address");
        return false;
    }

    // Perform login logic here
    // ...

    // Prevent form submission (for demonstration purposes)
    return false;
}
</script>
</head>
<body>
    <h2>Login Form</h2>
    <form name="loginForm" onsubmit="return validateForm()">
        <label>Email:</label>
        <input type="email" name="email" required><br><br>

        <label>Password:</label>
        <input type="password" name="password" required><br><br>

        <input type="submit" value="Login">
    </form>
</body>
</html>

In the above example, we have a login form with two fields: email and password. The `validateForm()` function is called when the form is submitted.

Inside the `validateForm()` function, we retrieve the values of the email and password fields using `document.forms["loginForm"]["email"].value` and `document.forms["loginForm"]["password"].value`, respectively.


We then use a regular expression (`emailRegex`) to validate the email format. In this example, we use a simple regular expression that checks if the email has the basic structure of `something@domain.com`. If the email does not match this format, we display an alert message and return `false` to prevent the form from being submitted.

In a real-world scenario, you would perform the actual login logic inside the `validateForm()` function. This might involve making an AJAX request to a server-side script to verify the credentials and handle the authentication process.

Please note that client-side validation is a useful addition for improving the user experience, but it should always be accompanied by server-side validation to ensure security and data integrity.


OUTPUT-




About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext