We have learned that HTML5 input elements can be restricted using pattern.
<form action="sample-input.php" method="post" target="_blank">
<p>
<label>
Zip Code:
<input name="sampleName" pattern="\d{3}-\d{4}" title="Please enter the zip code in the order of "3 digits, hyphen (-) and 4 digits" such as "123-4567".US>" >
</label>
</p>
<p><input type="submit" value="send">/p>
</form>
Is there any way that this happens with type="button" instead of type="submit"?
Or is it impossible to invoke an error message the moment you enter a character that is not applicable while typing text before pressing submit?
For browsers that support reportValidity()
such as Google Chrome and Opera, an error will appear in the same UI as when you press the submit button just by calling it.
<form action=...>
<input type="button" value="validation" onclick="this.form.reportValidity()">
If reportValidity()
is not available, you must issue an error message with your own code.
<form action=...>
<input type="button" value="validation" onclick="report(this.form)">
<script>
function report (form) {
if(form.sampleName.validity.valid)
return;
// alert() is not a good UI and should actually be displayed in a better way.
alert(form.sampleName.validationMessage+form.sampleName.title);
form.sampleName.focus();
}
</script>
You should do the same with the input
event handler.
Example without reprotValidity()
:
<form action=...>
<input name="sampleName" oninput="report(this)"...>
<script>
function report (input) {
if(input.validity.valid)
return;
// alert() is not a good UI and should actually be displayed in a better way.
alert(input.validationMessage+input.title);
input.focus();
}
</script>
© 2025 OneMinuteCode. All rights reserved.