KnockoutJS Custom Binding Click Submit Form Validation

I was recently researching which client-side form validation technique to use with a webpage HTML form, and found numerous open source plugins and extensions to jQuery, knockoutJS, angularJS and more. They all accomplish my requirement in different ways, but I wanted the standard way. As of October 28th 2014, HTML5 was released from the WC3. HTML5 adds several new input types and will also perform validation. This was a perfect candidate because it has the backing of WC3 and most modern browsers (mobile and desktop) have partial or full support.

Therefore, support from browsers will only get better. However there are some compromises that should be noted using this solution (versus the opensource plugins/extensions):

  • Your error messages are implemented by the browser, so you are at the mercy of their theme/styling guidelines.
  • From the browser’s I’ve tested, the error messages come in a popup that goes away after interaction (focus or clicking elsewhere).
  • If several inputs are invalid, it will only show the popup to the first invalid input, then once it’s fixed, you must resubmit to see the next invalid input.

If you can live with those compromises, then I recommend using HTML5 input components validation. Please note you should always validate your inputs server side as well, because you can never trust what is being submitted to your server (malicious users can bypass client side validation easily).

Now the main reason of this post was to provide a way to submit a <form> without “needing” a <input type=”submit” …/>. Because form validation needs the submit button to exist within the form, however new frameworks and libraries sometimes use anchor (<a>) to submit. I wanted an easy way to allow using an anchor to submit my form, but still use HTML5 form validation. So I wrote a knockout binding handler which will do just that.

You can get the custom binding handler here. It has no dependencies, but will take advantage of jQuery if it’s found. Usage is as simple:

<form name="myForm">
...
<a href="#" data-bind="clickSubmit: 'myForm'">Submit</a>
</form>

And you can exclude the parameter ‘myForm’ , if you are using jQuery.

You can test it out with the jsFiddle below: