Custom validation allows you to define your own validation rules for form fields. This can be useful when you have specific requirements that are not covered by built-in validation methods. For example, you may want to validate that a username is unique or that a phone number is in a specific format.
To implement custom validation, you can use JavaScript to define a function that checks the validity of a form field. This function should return true
if the field is valid and false
if it is not. Here's an example of how to implement custom validation for a password input field:
JAVASCRIPT
1function validatePassword(password) {
2 // Custom validation logic
3 if (password.includes('123456')) {
4 return false;
5 }
6 return true;
7}
8
9const passwordInput = document.getElementById('password');
10
11passwordInput.addEventListener('input', function() {
12 const password = passwordInput.value;
13 if (validatePassword(password)) {
14 passwordInput.setCustomValidity('');
15 } else {
16 passwordInput.setCustomValidity('Password is not valid');
17 }
18});