HomeHTML and CSSHow to Create Multi Step Form HTML & Js

How to Create Multi Step Form HTML & Js

How to Create Multi Step Form HTML & Js

Creating a Multi Step Form with responsive design and an animated background involves using HTML for the structure, CSS for styling, and possibly some JavaScript for managing the form steps.

To validate inputs in the Multi Step Form, you can use JavaScript to ensure that the user has entered valid data before proceeding to the next step or submitting the form. Below is an enhanced version of the previous code, including validation.

To display error messages alongside invalid input fields, you can enhance the JavaScript and CSS from the previous example. Here’s how you can do it:

To implement a password strength check in the Multi Step Form, you’ll need to enhance the JavaScript code to evaluate the password’s strength based on certain criteria, such as length, inclusion of uppercase and lowercase letters, numbers, and special characters. You can also provide real-time feedback to the user about the strength of their password.

Create index.html file and copy code and paste code our layout.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multi-Step Form in Javascript / Mycodingtutorial</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="form-container">
        <form id="multiStepForm">
            <div class="form-step active" id="step1">
                <h2>Step 1</h2>
                <div class="form-group">
                    <input type="text" id="firstName" placeholder="First Name" required>
                    <small class="error-message"></small>
                </div>
                <div class="form-group">
                    <input type="text" id="lastName" placeholder="Last Name" required>
                    <small class="error-message"></small>
                </div>
                <button type="button" class="next-btn">Next</button>
            </div>
            <div class="form-step" id="step2">
                <h2>Step 2</h2>
                <div class="form-group">
                    <input type="email" id="email" placeholder="Email" required>
                    <small class="error-message"></small>
                </div>
                <div class="form-group">
                    <input type="tel" id="phone" placeholder="Phone Number" required>
                    <small class="error-message"></small>
                </div>
                <button type="button" class="prev-btn">Previous</button>
                <button type="button" class="next-btn">Next</button>
            </div>
            <div class="form-step" id="step3">
                <h2>Step 3</h2>
                <div class="form-group">
                    <input type="password" id="password" placeholder="Password" required>
                    <small class="error-message"></small>
                    <div id="password-strength">
                        <span></span>
                        <span></span>
                        <span></span>
                        <span></span>
                    </div>
                    <small id="strengthMessage" class="strength-message"></small>
                </div>
                <div class="form-group">
                    <input type="password" id="confirmPassword" placeholder="Confirm Password" required>
                    <small class="error-message"></small>
                </div>
                <button type="button" class="prev-btn">Previous</button>
                <button type="submit" class="submit-btn">Submit</button>
            </div>
        </form>
    </div>
    <script src="script.js"></script>
</body>
</html>

Create style.css file and copy code and paste code our layout.

body {
    margin: 0;
    padding: 0;
    font-family: Arial, sans-serif;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background: linear-gradient(135deg, #ff6b6b, #f7b733);
    animation: backgroundAnimation 10s infinite alternate;
}

@keyframes backgroundAnimation {
    0% { background: linear-gradient(135deg, #ff6b6b, #f7b733); }
    100% { background: linear-gradient(135deg, #6bffb6, #3357f7); }
}

.form-container {
    background: white;
    padding: 30px;
    border-radius: 10px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
    max-width: 400px;
    width: 100%;
}

.form-step {
    display: none;
}

.form-step.active {
    display: block;
}

input {
    width: 100%;
    padding: 10px;
    margin: 10px 0;
    border: 1px solid #ccc;
    border-radius: 5px;
}
.error-message {
    color: red;
    font-size: 0.875em;
    margin-top: 5px;
    display: none; /* Initially hidden */
}

input.invalid {
    border-color: red;
}

input.invalid + .error-message {
    display: block;
}

button {
    padding: 10px 15px;
    margin-top: 10px;
    border: none;
    border-radius: 5px;
    background-color: #ff6b6b;
    color: white;
    cursor: pointer;
    width: 100%;
}

button:hover {
    background-color: #f7b733;
}

@media (max-width: 600px) {
    .form-container {
        padding: 20px;
    }

    input, button {
        padding: 8px;
    }
}
input.invalid {
    border-color: red;
}
#password-strength {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
}

#password-strength span {
    display: block;
    height: 5px;
    width: 22%;
    border-radius: 5px;
    transition: background-color 0.3s;
}

.strength-weak span:nth-child(1),
.strength-weak span:nth-child(2),
.strength-medium span:nth-child(1),
.strength-medium span:nth-child(2),
.strength-medium span:nth-child(3),
.strength-strong span:nth-child(1),
.strength-strong span:nth-child(2),
.strength-strong span:nth-child(3),
.strength-strong span:nth-child(4) {
    background-color: #ff6b6b;
}

.strength-medium span:nth-child(3),
.strength-strong span:nth-child(4) {
    background-color: #f7b733;
}

.strength-strong span:nth-child(4) {
    background-color: #6bffb6;
}

.strength-message {
    margin-top: 5px;
    font-size: 0.875em;
    color: #666;
}
Multi Step Form

Create Script.js file and copy code and paste code our layout.

document.addEventListener('DOMContentLoaded', function () {
    const nextBtns = document.querySelectorAll('.next-btn');
    const prevBtns = document.querySelectorAll('.prev-btn');
    const formSteps = document.querySelectorAll('.form-step');
    const form = document.getElementById('multiStepForm');
    const passwordInput = document.getElementById('password');
    const strengthMessage = document.getElementById('strengthMessage');
    const passwordStrength = document.getElementById('password-strength');
    let currentStep = 0;

    passwordInput.addEventListener('input', updatePasswordStrength);

    nextBtns.forEach((btn) => {
        btn.addEventListener('click', () => {
            if (validateStep()) {
                formSteps[currentStep].classList.remove('active');
                currentStep = (currentStep + 1) % formSteps.length;
                formSteps[currentStep].classList.add('active');
            }
        });
    });

    prevBtns.forEach((btn) => {
        btn.addEventListener('click', () => {
            formSteps[currentStep].classList.remove('active');
            currentStep = (currentStep - 1 + formSteps.length) % formSteps.length;
            formSteps[currentStep].classList.add('active');
        });
    });

    form.addEventListener('submit', function (event) {
        if (!validateStep()) {
            event.preventDefault();
        }
    });

    function validateStep() {
        let valid = true;
        const inputs = formSteps[currentStep].querySelectorAll('input');
        inputs.forEach(input => {
            const errorMessage = input.nextElementSibling;
            if (!input.checkValidity()) {
                valid = false;
                input.classList.add('invalid');
                errorMessage.textContent = getErrorMessage(input);
                errorMessage.style.display = 'block';
            } else {
                input.classList.remove('invalid');
                errorMessage.style.display = 'none';
            }
        });
        return valid;
    }

    function getErrorMessage(input) {
        if (input.validity.valueMissing) {
            return `${input.placeholder} is required.`;
        }
        if (input.validity.typeMismatch) {
            if (input.type === 'email') {
                return `Please enter a valid email address.`;
            }
            if (input.type === 'tel') {
                return `Please enter a valid phone number.`;
            }
        }
        if (input.type === 'password' && input.id === 'confirmPassword') {
            const password = document.getElementById('password').value;
            if (input.value !== password) {
                return `Passwords do not match.`;
            }
        }
        return `Invalid input.`;
    }

    function updatePasswordStrength() {
        const value = passwordInput.value;
        let strength = 0;
        let strengthClass = '';

        if (value.length >= 8) strength++;
        if (/[A-Z]/.test(value)) strength++;
        if (/[0-9]/.test(value)) strength++;
        if (/[^A-Za-z0-9]/.test(value)) strength++;

        switch (strength) {
            case 1:
                strengthClass = 'strength-weak';
                strengthMessage.textContent = 'Weak';
                break;
            case 2:
                strengthClass = 'strength-medium';
                strengthMessage.textContent = 'Medium';
                break;
            case 3:
                strengthClass = 'strength-medium';
                strengthMessage.textContent = 'Medium';
                break;
            case 4:
                strengthClass = 'strength-strong';
                strengthMessage.textContent = 'Strong';
                break;
            default:
                strengthMessage.textContent = '';
                break;
        }

        passwordStrength.className = '';
        if (strengthClass) {
            passwordStrength.classList.add(strengthClass);
        }
    }
});

HTML

  • The form contains two password fields: one for entering the password and one for confirming it.
  • Error messages are displayed in <small> elements right below the input fields.
  • A password strength indicator is provided, consisting of four span elements.

CSS

  • Styles are applied to the form, inputs, error messages, and the password strength indicator.
  • The password strength indicator changes color based on the strength of the entered password.

JavaScript

showError(): This function displays an error message below a specific input and adds the invalid class to the input.

updatePasswordStrength(): This function checks the entered password’s length, presence of uppercase letters, numbers, and special characters. It updates the strength indicator and message based on the password’s strength.

validateForm(): This function checks if the form is valid when the user submits it. It verifies that the passwords match and that the password is not too weak. If any validation fails, an error message is displayed, and the form submission is prevented.

clearErrorMessages(): This function clears all previous error messages and removes the invalid class from the inputs.

Conclusion

This implementation provides users with real-time feedback on the strength of their password. It encourages the creation of stronger passwords by showing a clear visual and textual indication of password strength as they type. This feature enhances security and usability, guiding users to create passwords that are more resilient against potential attacks.

Related Post

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Must Read

CATEGORY

spot_img