Quick-Start Guide: Custom Validations in Rails 6

Allene Norton
3 min readJan 26, 2021

Rails allows you to add validations to any of your models. Rails comes with a built in set of validations you can learn more about here. But wait! What if you don’t want to use them, or have a use case where you need to write a custom validation? Fear not, this guide will show you how.

Model: Method

You will want to start by writing your validation method in the model you want to validate. Name it descriptively in keeping with best practices. You can write whatever you need to inside the method. For my use case, I needed to validate that the user has checked at least one box in a check-box collection on a form for project creation. The collection contains a list of skills that act as tags for the project that are stored in an array, you can read my blog on tagging in Rails 6 here.

When a check-box collection is in a form, it returns an array with ’0' at each index where a box was left unchecked, and the value at each index of what was checked. Something like: [0, 0, ‘basketball’, 0, ‘boxing’, 0] if it was a collection of sports and only basketball and boxing were checked.

In order to validate that at least one box was checked, you need to write logic to see if all boxes are blank. Next, before your conditional logic, add your error to Rails’ built-in errors. More info on errors in Rails can be found here. Check out the example below.

example method checks if a skill in the list is unchecked

Validates vs. Validate

Remember, Rails already comes with its own set of built-in validations. They usually validate the presence or uniqueness of a model’s attribute, like a new user’s email address for example.

example of Rails’ built-in validations

For custom validations, however, you want to use the singular ‘validate’ with your custom validation method name.

example custom validation

These validations will go at the top of your model, and your method can be anywhere in the mix below. Make sure you are defining your validations in the model, not the controller.

Validate On Controller Action

If you only need to validate when a certain controller action occurs, on creation or when updating for example, you can do that as well! You will still use the singular ‘validate’, followed with ‘on: :<your_action_here>’. The validation will only occur on these actions.

custom validation on action

For my use case, I only need to make sure that the creator of a project has associated at least one skill when submitting the ‘Create Project’ form. Setting the validation to happen on only the create action in my projects controller was exactly what I needed to do.

That’s it! My form now throws an error if I try to create a project without associating at least one skill.

--

--

Allene Norton

Full stack developer and Flatiron graduate who recently made the jump from a career as a professional musician and audio engineer | Austin, TX