Using Basic and Custom Rails Validations

Rails Validations

In Rails, validations are special method calls defined at the top of the model class. Validations protect your database by preventing model instances from being saved to the database if they contain invalid data. Rails uses ActiveRecord to execute these validations. Keep in mind that AR validations are not the same as database validations, which check for things such as string length, data type, etc.

In the following post I’m going to cover implementing both basic and custom Rails validations. I had a tough time figuring out how to make the custom validations work since there was a lack of detailed information about them.

Here’s an example of a basic validation in Rails:

The database failed to commit this record because we created the model instance without a name. We can see the error message by accessing the errors object associated with the instance.

We can also access error attributes individually:

Custom Validations

Sometimes Rails’ basic validations aren’t enough. The good news is you can make your own validations! Below are three common ways to implement custom validations.

1. Use #validate for quick custom validations that you can extract later. This is a simple solution because you only need to define an instance method in the model file, which is invoked by #validate.

2. Create a subclass of ActiveModel::EachValidator and invoke it using a key in the options hash. This is best for validating a single attribute on one model, especially one you’re using built in validators for.

In the example below, we check to see if a person’s email address uses the @gmail.com domain.

3. Create a subclass of the ActiveModel::Validator class and invoke it with #validates_with. This approach is best if you need more complex validations (but I used a simple validation below).

If you decide to go with option 2 or 3, you’ll need to keep your files in a separate folder to ensure things stay DRY. I recommend using <root>/app/validators to store your custom validations, though some people like to use <root>/lib/validators.

You’ll also need to make a small change to your  file so Rails knows about your custom validators. If you use the /lib directory, be sure to change the code accordingly.

Check out this GitHub repository to see the validations in action.

Leave a Reply

Your email address will not be published. Required fields are marked *