Using validate
with a block
class Foo < ApplicationRecord
validate do
if ERROR_CONDITION
errors.add(:some_attribute, :bar)
end
end
end
OR using validate
with a method
class Foo < ApplicationRecord
validate :some_custom_validation_name
private
def some_custom_validation_name
if ERROR_CONDITION
errors.add(:some_attribute, :bar)
end
end
end
errors.add
can be used like the following:
errors.add(ATTRIBUTE_NAME, SYMBOL)
- SYMBOL corresponds to the
message
name. See the message
column here in this table
i.e. this can be :blank
, :taken
, :invalid
, or :bar
(your custom message
name)
errors.add(:some_attribute, :taken)
# => ["has already been taken"]
errors.add(:some_attribute, :invalid)
# => ["has already been taken", "is invalid"]
errors.add(:some_attribute, :bar)
# => ["has already been taken", "is invalid", "Blah blah"]
errors.add(ATTRIBUTE_NAME, SYMBOL, HASH)
same as above except that you can also pass in arguments to the message. See the interpolation
column here in the same table that you'll need to use.
errors.add(:some_attribute, :too_short, count: 3)
# => ["is too short (minimum is 3 characters)"]
errors.add(:some_attribute, :confirmation, attribute: self.class.human_attribute_name(:first_name))
# => ["is too short (minimum is 3 characters)", "doesn't match First name"]
errors.add(ATTRIBUTE_NAME, STRING)
or pass a custom message string
errors.add(:some_attribute, 'is a bad value')
# => ["is a bad value"]
Also, assuming that you intend to pass in :bar
as argument to your validation like in your example, then you can use a custom validator:
# app/validators/lorem_ipsum_validator.rb
class LoremIpsumValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
if ERROR_CONDITION
record.errors.add(attribute, options[:message])
end
end
end
# app/models/foo.rb
class Foo < ApplicationRecord
validates :some_attribute, lorem_impsum: { message: :bar }
# or multiple attributes:
validates [:first_name, :last_name], lorem_impsum: { message: :bar }
# you can also combine the custom validator with any other regular Rails validator like the following
# validates :some_attribute,
# lorem_impsum: { message: :bar },
# presence: true,
# length: { minimum: 6 }
end