Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Javascript Example to Validate Multi-Step HTML5 Form With Custom Error Messages in Browser

Posted on March 19, 2023

 

Welcome folks today in this blog post we will be implementing multi-step html5 form input fields validation and will be showing the custom error messages in browser using javascript. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to make an index.html file and copy paste the following code

 

`

index.html

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<style>
    .form {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin: auto;
        max-width: 600px;
        padding: 20px;
        border: 1px solid #ccc;
        border-radius: 5px;
    }
 
    .step {
        display: none;
    }
 
    .step.active {
        display: flex;
        flex-direction: column;
        align-items: center;
    }
 
    .error {
        border: 2px solid red;
    }
 
    .error-message {
        color: red;
        margin-top: 5px;
    }
</style>
 
<form id="myForm" class="form" novalidate>
 
    <div class="step active">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        <span id="name-error" class="error-message"></span>
        <button type="button" class="next">Next</button>
    </div>
 
    <div class="step">
        <label for="email">Email:</label>
        <input type="email" id="email" name="email">
        <span id="email-error" class="error-message"></span>
        <button type="button" class="prev">Previous</button>
        <button type="button" class="next">Next</button>
    </div>
 
    <div class="step">
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" required>
        <span id="password-error" class="error-message"></span>
        <button type="button" class="prev">Previous</button>
        <button type="button" class="next">Next</button>
    </div>
    
    <div class="step">
        <label for="address">Address:</label>
        <input type="text" id="address" name="address" required>
        <span id="address-error" class="error-message"></span>
        <button type="button" class="prev">Previous</button>
        <button type="submit">Submit</button>
    </div>
 
</form>

 

 

 

As you can see we have four input fields in each step firstly we allow the user to enter the username and then we allow the user to enter the email address and password in the next step and lastly we enter the address in the final step. And then we have the submit button to submit the details of the user. And also we are styling the form using custom css.

 

 

 

 

And now we need to write the javascript code to implement the form validation as shown below

 

 

script.js

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
const form = document.getElementById("myForm");
    const steps = form.querySelectorAll(".step");
    const nameInput = form.querySelector("#name");
    const emailInput = form.querySelector("#email");
    const passwordInput = form.querySelector("#password");
    const addressInput = form.querySelector("#address");
 
    // Show the first step initially
    showStep(0);
 
    // Handle "Next" button clicks
    form.addEventListener("click", function (event) {
        if (event.target.classList.contains("next")) {
            const currentStep = event.target.closest(".step");
            const nextStep = currentStep.nextElementSibling;
 
            if (validateStep(currentStep)) {
                showStep(Array.from(steps).indexOf(nextStep));
            }
        }
    });
 
    // Handle "Previous" button clicks
    form.addEventListener("click", function (event) {
        if (event.target.classList.contains("prev")) {
            const currentStep = event.target.closest(".step");
            const prevStep = currentStep.previousElementSibling;
 
            showStep(Array.from(steps).indexOf(prevStep));
        }
    });
 
    // Handle form submissions
    form.addEventListener("submit", function (event) {
        event.preventDefault();
 
        if (validateForm()) {
            alert("Form submitted successfully!");
        }
    });
 
    // Function to show a given step
    function showStep(index) {
        // Hide all steps
        for (let step of steps) {
            step.classList.remove("active");
        }
 
        // Show the given step
        steps[index].classList.add("active");
    }
 
    // Function to validate a single step
    // Function to validate a single step
    function validateStep(step) {
        let isValid = true;
 
        // Reset errors
        const errorMessages = step.querySelectorAll(".error-message");
        for (let errorMessage of errorMessages) {
            errorMessage.textContent = "";
        }
 
        // Validate inputs
        const inputs = step.querySelectorAll("input");
        for (let input of inputs) {
            if (input.checkValidity()) {
                input.classList.remove("error");
            } else {
                input.classList.add("error");
                isValid = false;
 
                // Display error message
                const errorMessage = step.querySelector(`#${input.id}-error`);
                errorMessage.textContent = input.validationMessage;
            }
        }
 
        return isValid;
    }
 
 
    // Function to validate the entire form
    function validateForm() {
        let isValid = true;
 
        // Validate each step
        for (let i = 0; i < steps.length; i++) {
            if (!validateStep(steps[i])) {
                isValid = false;
                showStep(i);
                //break;
            }
        }
 
        return isValid;
    }
 
    // Email validation using regular expression
    emailInput.addEventListener("input", function () {
        if (emailInput.checkValidity()) {
            emailInput.classList.remove("error");
            document.querySelector("#email-error").textContent = "";
        } else {
            emailInput.classList.add("error");
            document.querySelector("#email-error").textContent =
                "Please enter a valid email address";
        }
    });

 

 

 

 

 

As you can see we are getting all the references of all the dom elements and then we are attaching the event listeners to the input elements and then we are validating the data for each step and then showing the custom error messages.

 

 

Recent Posts

  • Javascript Example to Validate Multi-Step HTML5 Form With Custom Error Messages in Browser
  • Javascript Wavesurfer.js Example to Generate Audio Waveform of Selected Audio File in Browser
  • Javascript Fabric.js Example to Export Drawing Canvas to Image & PDF Document in Browser
  • Python 3 Flask-WTF Example to Implement Form Validation and Show Custom Error Messages in Browser
  • Python 3 Flask Jinja2 Template Project to Implement HTML5 Form Validation & Show Custom Error Messages in Browser
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme