Introduction#
When performing data validation on input controls in a <form>
according to Bootstrap - Forms - Validation, you can add common native validation attributes such as required
, minlength
, and maxlength
to the controls.
When we have more complex business logic, we can also customize validation rules through JavaScript, allowing for greater freedom in form validation. This article will introduce how to implement this.
Usage#
function validate(inputID) {
const input = document.getElementById(inputID);
const validityState = input.validity;
if (validityState.valueMissing) {
input.setCustomValidity("You must fill this out!");
} else if (validityState.rangeUnderflow) {
input.setCustomValidity("We need a larger number!");
} else if (validityState.rangeOverflow) {
input.setCustomValidity("Too large!");
} else {
input.setCustomValidity("");
}
// Immediately pop up the native HTML control validation prompt
input.reportValidity();
}
// Validate password rules on blur
$('#password').on('blur', function (e) {
const password = $(this).val();
// A custom validation method
if (validatePassword(password)) {
// Password meets requirements
// If there are no errors, set the message to an empty string so that form validation can pass, meaning checkValidity() returns true
this.setCustomValidity('');
} else {
// Password does not meet requirements
// As long as the error message is not empty, the form will not validate (checkValidity() returns false) and will not be submitted
// Since we are currently using Bootstrap's form validation prompts, the error message given here will not actually display on the page, it's just to make the current control fail validation
this.setCustomValidity('Passwords must match');
}
// reportValidity() will immediately pop up the native HTML control validation prompt, but since we are currently using Bootstrap's validation prompts, we do not call it to trigger the native validation prompt
//this.reportValidity();
});