I'm trying to use HTML5 client-side validation (i.e. inside a form), but cannot see how to display the validation error bubbles programatically.
Consider the following:
<form id="myForm">
<input type="text" id="number" min="1" max="10" step="3" required>
</form>
If there is a canonical submit
button (i.e <input type="submit">
), and there are validation errors, the user-agent will halt the submit and show UI to the user:
But, if instead of a using a submit
input, the user is clicking an anchor that executes javascript (i.e. ASP.net Webforms):
<a href='javascript:SaveChanges()'>Save Quantity</a>
<script>
function SaveChanges()
{
var form = document.getElementById('myForm');
if (form === null) return;
if (!form.checkValidity())
{
//We reach here, but no UI is displayed
return;
}
form.submit();
</script>
The issue is that while
form.checkValidity();
does check the form's validity (returning false
if it's not valid), it does not trigger the UI displays.
And now we have our question. Submitting through
<input type="submit">
works (halts and shows UI)<button type="submit>
works (halts and shows UI)form.submit
doesn't work (doesn't halt; doesn't show UI)form.checkValidity()
doesn't work (doesn't show UI)How to programmatically display HTML5 client-side form validation error bubbles?
jsFiddle for all of the above
This might not be the cleanest way, but I added a hidden submit button and programmatically trigger the click event on it.
I updated the jsfiddle this way:
Add a new submit button #fakeButton with a css class:
.fakeButton{
display:none;
}
Add a new link triggering it through a javascript function:
function DoFakeButtonClick()
{
var button = $('#fakeButton');
if (button === null)
return;
button.click();
}
It works pretty well, i think it is currently the only way to do this programmatically
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With