JSFiddle - React, Tailwind, and code Playground
HTML
<form id="frmTest" action="#" method="post">
<input type="tel" id="txtPhone" name="txtPhone" maxlength="20"
placeholder="555-555-5555" title="555-555-5555"
pattern="\d{3}-\d{3}-\d{4}" required>
<input type="submit" id="btnSubmit">
</form>
JavaScript
window.addEventListener("DOMContentLoaded", function(){
var theForm = document.querySelector("#frmTest");
var thePhone = document.querySelector("#txtPhone");
var theSubmitButton = document.getElementById("#btnSubmit");
// Because forms can be submitted via submit buttons but also from pressing ENTER,
// we need to make sure the form has gone through custom validation before submit
// actually happens. So, we'll validate on the submit button's click event as well
// as the form submit.
btnSubmit.addEventListener("click", validate);
theForm.addEventListener("submit", validate);
function validate(evt){
// Reset the validity of the phone number
txtPhone.setCustomValidity("");
// Check to see if the form is INVALID for any reason
if(!theForm.checkValidity()){
// Check to see if it is the phone number that is the problem:
if(!txtPhone.validity.valid){
// Set up your own custom error message from whatever source you like
// Here, it's just hard coded:
txtPhone.setCustomValidity("There is no way that is a valid phone number!");
}
}
}
});