Is it more sensible to use client-side validations in Rails?

3

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

    
asked by anonymous 20.05.2014 / 21:13

3 answers

7

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

I recommend that you validate in at least 2 places:

  • Database, using constraints , foreign keys and unique indexes li>
  • Application (Rails model layer)

Placing validation in JavaScript is more convenient for the user (he does not need to submit the form to see that some field is incorrect), this is at your discretion. But what will guarantee safety are the two approaches above.

I always suggest putting safety and reliability above performance. What's more, I do not think the performance difference is significant in this case.

See these two related questions:

Tip :

You can use gem foreigner to have integration of foreign keys with the Rails database versioning ).

Remember that there are methods that do not trigger 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 validation this way:

- save(validate: false)

Source: Rails Official Validation Guide

    
20.05.2014 / 21:33
6

Ideally you should do the E client validations on the server.

Validating the client side is legal for the reasons you said (save bandwidth, shorter response time, cooler UX, etc.), but you also need to validate the server, even if your client usually does not need to do the requisitions.

The reason is security, since it is fairly simple for a malicious person to be able to make malicious HTTP requests directly to your server, ignoring the client's "protection."

    
20.05.2014 / 21:19
5

Do a validation on both sides.

If client validation fails for some reason, you will still have it on the server to revalidate and ensure you have no problems.

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

Better sin by over-validating than not validating.

    
20.05.2014 / 21:17