How to prevent a user holding the enter key on a form from slamming my site with requests?

2.3k Views Asked by At

I have the following jquery code in use to submit a form if the enter key is pressed:

$('body').on('keypress', 'input', function(event) {
    if (event.which === 13) {
        event.preventDefault();
        $(this).closest('form').submit();
    }
});

Also, I have my login page set up to .focus() on the username field on page load.

So if a user just holds on the 'enter' key, it will submit, fail, return, focus, submit, repeat.

I could put the keypress event to only trigger when in the password field, but I'd rather find a way to detect a long keypress or something to prevent this scenario.

2

There are 2 best solutions below

2
Kevin B On

Throttle the event so it can only happen once per second.

var timer;
$('body').on('keypress', 'input', function(event) {
    var self = this;
    if (event.which === 13) {
        event.preventDefault();
        clearTimeout(timer);
        timer = setTimeout(function(){
            $(self).closest('form').submit();                
        },1000)
    }
});
3
MatRt On

Like Blender says, for the majority of browser, it is a default behaviour, for an input in the form, to submit the form, when you press enter key (it is like clicking on an input with a submit type).

Your fist code seems a little bit useless because it is preventing the default behaviour (submitting the form), but finally submit the form.

The timeout solution is not bad but too complex in my point of view for a such problem.

Your page is a login page, that meens that you want to allow login try when login and password are filled. Moreover, you don't want to allow multiple submit of the same page in a short delay.

You could write a piece of code like:

// Listening on submit event of the form
$("#FORM_ID").submit(function(submitEvent) {

    // Check if the login and password are not empty
    if (($.trim($("#LOGIN_INPUT_ID").val())).length == 0 ||
        ($.trim($("#PASSWORD_INPUT_ID").val())).length == 0)
    {
        // login or password is empty -> cancel the submit
        submitEvent.preventDefault();

        // TODO : warn user with a message
        // like "Please, fill login and password first !"

        return false;
    }

    // Avoid multiple submit at the same time
    // (for stupid guy clicking 10 times in 1 s)
    if ($(this).hasData('alreadySubmitted'))
    {
        // The form is currently already submit -> cancel the submit
        submitEvent.preventDefault();
        return false;
    }

    // Set the form "submitted"
    $(this).data('alreadySubmitted', true);

   // Let the submit do his job...
   return true;
});