15

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

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.