Having dedicated a significant portion of the afternoon to researching the same topic, it appears that there is a scarcity of information on implementing custom JS validation with the default Bootstrap validation. Based on my findings, I have identified two potential methods:
- Utilizing the
pattern
attribute on the element
- Incorporating your own JS validation within the
checkValidity()
expression
Pattern Attribute
When creating an input
, it is possible to define a pattern attribute for the element.
Referencing the MDN pattern article:
<p>
<label>Enter your phone number in the format (123) - 456 - 7890
(<input name="tel1" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit area code" size=&qout;2"/>) -
<input name="tel2" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit prefix" size=&qout;2"/> -
<input name="tel3" type="tel" pattern="[0-9]{4}" placeholder="####" aria-label="4-digit number" size=&qout;3"/>
</label>
</p>
This example illustrates the structure for a North American phone number, with each section denoted by a specified pattern attribute indicating expectations for 3-digits, 3-digits, and 4-digits respectively.
JS Validation
Upon invoking the checkValidity()
method, integrate custom JS validation logic to reject form submission if necessary.
const myValidation = someValidation()
if (!myValidation || !form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
For the someValidation()
function, remember to adjust the validation classes accordingly:
// valid input
const foo = document.getElementById("foo")
foo.classList.remove("is-invalid")
foo.classList.add("is-valid")
// invalid input
const bar = document.getElementById("bar")
bar.classList.add("is-invalid")
bar.classList.remove("is-valid")
However, I am still exploring how to completely suppress the validation framework from displaying an input as valid (indicated by a checkmark on the right side) despite setting the appropriate classes. It seems related to having an empty pattern attribute, which signifies that the field cannot be left blank, and may require triggering the element's reportValidity()
method: HTML Spec: reportValidity()
Conclusion
Evidently, leveraging the pattern attribute and RegEx is the recommended approach when working with this validation framework.
It is my hope that someone else can enhance this solution by offering a more effective strategy using pure JS techniques.