Client-Side Validation Powered By ActiveRecord

Chris Schmitz
2 min readAug 1, 2018

I’ve worked on a number of Ruby on Rails apps where I had validation rules defined on the server and the client. Inevitably, one of them gets out of sync and it is only noticed because of the confusing UX it provided on form validation messages in production.

I’m here today to share one way to tame this complexity. It’s possible to expose the validations in your ActiveRecord models to the client and use them to power your client-side validations.

Getting Validation Data

ActiveRecord models give you access to all of the validators assigned to them via #validators.

Every time you use validates or validates_with in a model it assigns a validator class for the validation rule. In the example above, you can see that we have the PresenceValidator assigned to User because we call validates :first_name, presence: true.

The validators expose the information we need to share with the client via #attributes and #options. This gives us the three key pieces of information we need to know about our validations.

  1. The attribute name (#attributes)
  2. The validation, inferred from the class name (PresenceValidator)
  3. The validation config (#options)

Defining Validation Rules as JSON

Now we can build a hash with the validation information which can be sent to the client as JSON. Here is an example of how this could be done.

Here is what this looks like when converted to JSON.

This is starting to look like a reasonable payload to deliver to the client!

Exposing Validations to the Client

Getting your validations into the client is as simple as calling to_json on the hash of validations we created and writing it to a JS file. We are writing this to a validations.js file and loading it with the rest of our JS. From here you can export as a module or expose in whatever way is easiest to consume in your app.

Here is an example rake task you could use to create this.

Now you have access to your validations and can work with them in your client code as needed.

Please Share

In most apps I’ve built I wished I had a way to keep validations in sync between the server and client. This is one way of tackling this problem, but I’m very interested to hear how others have approached it. Please share your experiences 👇 if you‘ve tried to solve a similar problem.

--

--