Password Matching Validation with Custom Error Messages
An example of how you can implement your own error messages using the constraint validation API.
by TJ VanToll
HTML
<form id="passwordForm" novalidate>
<fieldset>
<legend>Change Your Password</legend>
<ul>
<li>
<label for="password1">Password 1:</label>
<input type="password" required id="password1" />
<p class="error"></p>
</li>
<li>
<label for="password2">Password 2:</label>
<input type="password" required id="password2" />
</li>
</ul>
<input type="submit" />
</fieldset>
</form>
CSS
form { padding: 20px; width: 300px; overflow: hidden; }
fieldset { padding: 10px; border: 1px solid black; margin-bottom: 5px; }
li { padding: 10px; }
input[type=submit] { float: right; margin-top: 10px; }
.error { display: none; color: red; font-weight: bold; }
.submitted :invalid + .error { display: block; }
.submitted :invalid { border: 1px solid red; }
JavaScript
(function() {
var password1 = document.getElementById('password1');
var password2 = document.getElementById('password2');
var form = document.getElementById('passwordForm');
var checkPasswordValidity = function() {
if (password1.value != password2.value) {
password1.setCustomValidity('Passwords must match.');
updateErrorMessage();
} else {
password1.setCustomValidity('');
}
};
var updateErrorMessage = function() {
form.getElementsByClassName('error')[0].innerHTML = password1.validationMessage;
};
password1.addEventListener('change', checkPasswordValidity, false);
password2.addEventListener('change', checkPasswordValidity, false);
form.addEventListener('submit', function(event) {
if (form.classList) form.classList.add('submitted');
checkPasswordValidity();
if (!this.checkValidity()) {
event.preventDefault();
updateErrorMessage();
password1.focus();
}
}, false);
}());