Preventing duplicate form submissions with Parsley

I recently had a bug where a user managed to register twice on CompareVino in a matter of seconds, causing the confirmation page to break (as it was expecting one user for the given email address instead of two).

On closer inspection, the user in question had double clicked the register button causing two requests to be sent off - a fairly obvious behaviour that had somehow slipped my mind to prevent.

A quick Google and a global javascript handler disabling the submit button upon click seemed to be the best solution. The issue with such an approach is that if you make use of a javascript validation library (I'm using Parsley), if any of the validations fail, you end up with a form the can't be submitted until the page is refreshed. Far from ideal!

Instead, what you need to do is only disable the submit button if all the validations pass. This can be done fairly easily by subscribing to the Parsley form validated event and checking the validation result. In code, this translates into:

$.listen('parsley:form:validated', function(e){
    if (e.validationResult) {
        /* Validation has passed, prevent double form submissions */
        $('button[type=submit]').attr('disabled', 'disabled');

For reference, the Parsley initialisation code I've used to make Parsley work with Bootstrap 3 is the following:

    successClass: "has-success",
    errorClass: "has-error",
    classHandler: function (el) {
        return el.$element.closest(".form-group");
    errorsContainer: function (el) {
        return el.$element.closest(".form-group");
    errorsWrapper: "<span class='help-block'></span>",
    errorTemplate: "<span></span>"

Note the use of the class validate-form instead of an id. This way, once the Parsley setup code has been globally defined, you can annotate any form that needs validation / double submit prevention by simply adding the validate-form class to it.

Author image
About Jon Leigh
London Website

Hi, I'm Jon. I'm part of the Engineering team at Moneybox, a London based Fintech startup helping people to save and invest.

In my spare time, I've created CompareVino, a UK supermarket wine comparison website. If you like wine and buy it from a supermarket, you should definitely check it out.

If you want to get in touch, send me a message via Twitter