Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically display HTML5 client-side form validation error bubbles?

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.

enter image description here

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:

enter image description here

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

See also

  • How to programmatically display HTML5 client-side validation error bubbles?
  • Trigger standard HTML5 validation (form) without using submit button?
  • Triggering HTML5 Form Validation
like image 526
Ian Boyd Avatar asked Sep 18 '13 21:09

Ian Boyd


2 Answers

This might not be the cleanest way, but I added a hidden submit button and programmatically trigger the click event on it.

like image 120
Andy Avatar answered Nov 16 '22 17:11

Andy


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

like image 30
Dominique Avatar answered Nov 16 '22 17:11

Dominique