Is it wiser to use client-side validations in Rails?

Asked

Viewed 216 times

3

According to your own experience it is best to use validations on client-side? Because if we analyze, Rails, in the standard validations, sends the request, does the validation and then returns the errors. This process, despite not being time consuming (in local development), logic does not consume more server processing? It would not be better in terms of performance, to make the validations directly on client-side javascript?

3 answers

7


Be sure to validate on the server. If there is a bug in your application (or malicious attacks) and enter inconsistent data in the database, it will be very difficult to fix.

I recommend that you do validation in at least 2 places:

  • Data bank, through constraints (not null, Foreign Keys and Unique Indexes)
  • Application (Rails model layer)

Putting validation in Javascript is more of a convenience for the user (he doesn’t need to submit the form to see that some field is incorrect), that’s up to you. But what will ensure the same security are the two approaches above.

I always suggest putting safety and reliability above performance. Moreover, I do not believe that the difference in performance is considerable in this case.


See these two related questions:

Tip:

You can use the Gem Foreigner to integrate Foreign Keys with Rails database versioning (Migration).

Remember that there are methods that nay trigger the Rails validations:

- decrement!
- decrement_counter
- increment!
- increment_counter
- toggle!
- touch
- update_all
- update_attribute
- update_column
- update_columns
- update_counters

You can also explicitly skip the validation in this way:

- save(validate: false)

Source: Official Rails Guide to Validations

6

Ideal is that you make the customer validations And on the server.

Validating on the client side is cool precisely for the reasons you mentioned (save bandwidth, less response time, cooler UX, etc.), but you also need to validate the server, even if your client doesn’t usually end up having to make the requests.

The reason is security, since it’s quite simple for someone malicious to make malicious HTTP requests directly to your server, ignoring the client’s "protection".

5

Perform a validation on both sides.

If client validation fails for some reason, you’ll still have it on the server to revalidate and make sure it’s okay.

If the first validation passes, in theory, there would be no need to revalidate later, but this avoids some headaches as well.

Best sin over-validation of that which does not validate.

Browser other questions tagged

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