Real-time Form Validation
Showcase form validation that occurs as the user types, checking for valid email patterns and password strength, and providing immediate feedback on each input field.
document.getElementById('email').addEventListener('input', function(e) {
var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
document.getElementById('email-feedback').textContent = emailPattern.test(e.target.value) ? 'Valid email' : 'Invalid email';
});
This code snippet adds an 'input' event listener to an email input field. It uses a regular expression to test the input value against a basic email pattern each time the user types. It then updates the text content of the element with id 'email-feedback' to provide immediate feedback on whether the email is valid or not.
document.getElementById('password').addEventListener('input', function(e) {
// A very basic example of password strength checking
var strength = 'Weak';
var value = e.target.value;
if (value.length > 10 && /[A-Z]/.test(value) && /[0-9]/.test(value)) { strength = 'Strong'; }
else if (value.length > 5) { strength = 'Medium'; }
document.getElementById('password-feedback').textContent = 'Password strength: ' + strength;
});
This code snippet adds an 'input' event listener to a password input field. It checks the strength of the password based on length and the presence of uppercase letters and numbers. It updates the text content of the element with id 'password-feedback' with the password strength level as the user types.