<div class="p-4">
<form id="myform" action="javascript:void(0)">
<div>
<label for="myform_phone">Phone:</label>
<input type="tel" id="myform_phone" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required/>
</div>
<div class="mt-2">
<button type="submit">Submit</button>
</div>
</form>
</div>
var phone_input = document.getElementById("myform_phone");
phone_input.addEventListener('input', () => {
phone_input.setCustomValidity('');
phone_input.checkValidity();
});
phone_input.addEventListener('invalid', () => {
if(phone_input.value === '') {
phone_input.setCustomValidity('Enter phone number!');
} else {
phone_input.setCustomValidity('Enter phone number in this format: 123-456-7890');
}
});
This Pen doesn't use any external JavaScript resources.