Can someone suggest an HTML oninvalid Event Attribute work around in the context of my code?
That is because your pattern only accepts a single alphabet: [A-Za-z]
. To accept an alphabetical string that has length of 1 or more, you need to add a +
at the end, i.e. [A-Za-z]+
:
// This JS is only for demo purposes, so that a successful validation will not submit the form in the demo snippet
document.querySelector('#my-form').addEventListener('submit', e => {
console.log('Form valid! Will submit, but submission is prevented for demo purposes');
e.preventDefault();
});
<form id="my-form">
<div class="mb-3 text-white">
<label>Name</label>
<input type="text" name="name" pattern="[A-Za-z]+" oninvalid="alert('NAME ERROR: Please eneter characters only.');" required>
</div>
<button>Submit</button>
</form>
On a side note, I strongly suggest not using inline JS. What you want to do can be easily done in JS: and you can also store the intended error message in data-
attributes for convenience:
// This JS is only for demo purposes, so that a successful validation will not submit the form in the demo snippet
document.querySelector('#my-form').addEventListener('submit', e => {
console.log('Form valid! Will submit, but submission is prevented for demo purposes');
e.preventDefault();
});
document.querySelectorAll('input').forEach(el => {
const invalidMessageElement = el.nextElementSibling;
el.addEventListener('invalid', () => {
invalidMessageElement.textContent = el.dataset.invalidMessage;
invalidMessageElement.classList.add('visible');
});
el.addEventListener('input', () => {
invalidMessageElement.textContent = '';
invalidMessageElement.classList.remove('visible');
});
});
.invalid-message {
display: none;
color: red;
}
.invalid-message.visible {
display: inline;
}
<form id="my-form">
<div class="mb-3 text-white">
<label>Name</label>
<input type="text" name="name" pattern="[A-Za-z]+" required data-invalid-message="Please enter characters only."><span class="invalid-message"></span>
</div>
<div class="mb-3 text-white">
<label>Barcode</label>
<input type="text" name="barcode" required data-invalid-message="Please input barcode here."><span class="invalid-message"></span>
</div>
<div class="mb-3 text-white">
<label>Email</label>
<input type="email" name="email" required data-invalid-message"Please input email here."><span class="invalid-message"></span>
</div>
<button>Submit</button>
</form>