JavaScript Form Validation - Real-Time Validation


Real-time form validation is essential to provide a better user experience and ensure that user input is correct and meets the required criteria. In this guide, we'll explore how to perform real-time form validation using JavaScript and provide sample code to demonstrate the process.


HTML Form


First, let's create a simple HTML form that we want to validate in real-time:


<form id="validation-form">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<span id="username-error" class="error"></span>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<span id="email-error" class="error"></span>
<input type="submit" value="Submit">
</form>

JavaScript Real-Time Validation


Now, let's write JavaScript code to perform real-time validation of the form fields as the user types:


const form = document.getElementById('validation-form');
const usernameInput = document.getElementById('username');
const emailInput = document.getElementById('email');
const usernameError = document.getElementById('username-error');
const emailError = document.getElementById('email-error');
usernameInput.addEventListener('input', function () {
if (usernameInput.validity.valid) {
usernameError.textContent = '';
usernameError.classList.remove('error');
usernameError.classList.add('success');
} else {
showError(usernameInput, usernameError, 'Username is required.');
}
});
emailInput.addEventListener('input', function () {
if (emailInput.validity.valid) {
emailError.textContent = '';
emailError.classList.remove('error');
emailError.classList.add('success');
} else {
showError(emailInput, emailError, 'Please enter a valid email address.');
}
});
form.addEventListener('submit', function (event) {
if (!usernameInput.validity.valid) {
showError(usernameInput, usernameError, 'Username is required.');
event.preventDefault();
}
if (!emailInput.validity.valid) {
showError(emailInput, emailError, 'Please enter a valid email address.');
event.preventDefault();
}
});
function showError(input, errorElement, message) {
errorElement.textContent = message;
errorElement.classList.remove('success');
errorElement.classList.add('error');
}

Conclusion


Real-time form validation using JavaScript enhances the user experience by providing immediate feedback to users as they fill out a form. It ensures that user input is accurate and meets the required criteria.


Implement real-time form validation in your web applications to create user-friendly and error-free form submissions.