Friday, 10 January 2025

How to Validate Form Submission with JavaScript and Display a Success Message?

This is continution to my previous post (where we discussed about submitting the form data to a server). In this post, instead of submitting the form to a server, you can handle the form submission using JavaScript. By preventing the default form submission behavior, you can validate the data and show an alert message like "Registration Successful!!!!!!".

Here's an example of how to modify the form to call a JavaScript function on submission.

 

validate-form-data.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form with JavaScript</title>
    <script>
        // JavaScript function to handle form submission
        function handleFormSubmit(event) {
            // Prevent the default form submission behavior
            event.preventDefault();

            // Get form values
            const username = document.getElementById('username').value;
            const email = document.getElementById('email').value;
            const password = document.getElementById('password').value;

            // Simple validation (checking if fields are filled)
            if (username && email && password) {
                // Show success message
                alert('Registration Successful!!!!!!');
            } else {
                // Show error message if fields are missing
                alert('Please fill in all the fields.');
            }
        }
    </script>
</head>
<body>
    <h2>Registration Form</h2>
    <form onsubmit="handleFormSubmit(event)">
        <label for="username">Username:</label><br>
        <input type="text" id="username" name="username"><br><br>

        <label for="email">Email:</label><br>
        <input type="email" id="email" name="email"><br><br>

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

        <button type="submit">Register</button>
    </form>
</body>
</html>

 

Above snippet generate below screen.

 


 

Click on Register button, without adding the details, you will see below screen.

 



Add some detail and submit button, you will see below screen.

 


Explanation

1.   onsubmit="handleFormSubmit(event)": This attribute calls the handleFormSubmit JavaScript function when the form is submitted.

2.   event.preventDefault(): This prevents the form from actually submitting

3.   The function checks whether all fields (username, email, password) are filled. If they are, it shows an alert saying "Registration Successful!!!!!!". If any fields are missing, it shows a message asking the user to fill in all the fields.


Previous                                                    Next                                                    Home

No comments:

Post a Comment