When validating a form, it is often necessary to check the length of an input field to ensure that it meets certain requirements. For example, you may want to validate that a password is at least 8 characters long. Length validation can help provide a better user experience by giving immediate feedback when a user enters an invalid value.
In JavaScript, you can use the length
property of a string to check its length. Here's an example of how to perform length validation for a password input field:
JAVASCRIPT
1const passwordInput = document.getElementById('password');
2
3passwordInput.addEventListener('input', function() {
4 const password = passwordInput.value;
5 if (password.length < 8) {
6 passwordInput.setCustomValidity('Password must be at least 8 characters long');
7 } else {
8 passwordInput.setCustomValidity('');
9 }
10});