How can I prevent a user from submitting the same form multiple times?

Asked

Viewed 879 times

5

I have a form on a page, sometimes users can double-click the button to submit the form...

The form is a

@using (Ajax.BeginForm(...))
{
}

How can I prevent that from happening?

  • The best thing would be for you not to have problems with this happening, because otherwise it is possible attack your site doing this.

2 answers

1


The simplest way is, via Javascript, to detect that the form was sent and disable the Submit button.

Example (with jQuery):

$('input[type=submit]').click(function(botao) { $(botao).prop('disabled', true); });

But this meets only on the client side. For better usability it is better to use something more appropriate as, for example, replace a button with a "loading" or something of the kind. The example is just one Quick fix.

If the issue is not merely usability, but rather the validity of the form, you can mark your action with the attribute Antiforgerytoken, that will generate a specific key for that form request (and validated by ASP.NET itself in Submit).

  • 1

    The problem is the browser is disabled js.

  • 1

    @This is why we must always ensure the integrity of the data in the application and not trust the customer. As for the user, when disabling Javascript he needs to understand that will have a great impact on usability. On the other hand, this is becoming less common. Firefox, for example, removed in version 23 or 24 the JS disable field and screen images options, as they were very little used functions.

  • Really a normal user will always want to navigate with Javascript enabled. The only problem is malicious ones that purposefully disable javascript.

0

Can prevent this situation doing for example this:

<form onsubmit="if(typeof fSub !== 'undefined') return false; fSub = true;">

Note: You can declare the variable fSub overall to avoid type validation.

Anyway the validation has at all times to be done on the server side to prevent attacks.
It is bad practice to validate only one side.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.