DEV Community

Cover image for Boolean Validator for Rails
Mario
Mario

Posted on • Edited on

Boolean Validator for Rails

Rails doesn't come with a built-in boolean validator.
That means if we have boolean attribute and we set it to nil, it defaults to false, which is not necessarily what we want.

For example a SchrodingersCat model with a alive boolean attribute:

cat = SchrodingersCat.new(alive: nil)
cat.valid? # => true
Enter fullscreen mode Exit fullscreen mode

To solve that problem we can add a custom validator:

# app/validators/boolean_validator.rb
class BooleanValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    return if value.in? [false, true]

    record.errors.add attribute, :boolean
  end
end
Enter fullscreen mode Exit fullscreen mode

Then we can use that validator the same way as the built-in ones:

# app/models/schrodingers_cat.rb
class SchrodingersCat < ApplicationRecord
  validates :alive, boolean: true
end
Enter fullscreen mode Exit fullscreen mode

The error message can be defined for example in activerecord.errors.messages.boolean:

# config/locales/en.yml
en:
  activerecord:
    errors:
      messages:
        boolean: "must be boolean"
Enter fullscreen mode Exit fullscreen mode

The result:

cat = SchrodingersCat.new(alive: nil)
cat.valid? # => false
cat.errors.to_a # => ["Alive must be boolean"]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)