How to Customize Rails Activerecord Validation Error Message to Show Attribute Value

how to customize rails activerecord validation error message to show attribute value

2 things:

  1. The validation messages use the Rails I18n style interpolation, which is %{value}
  2. The key is value rather than name, because in the context of internationalization, you don't really care about the rest of the model.

So your code should be:

validates_uniqueness_of :name, :message => '%{value} has already been taken'

ActiveRecord: How to interpolate attribute value to a custom validation errror message?

The reason you are getting back BookVersion is because at this point, the validation is scoped to the Class and not the object you are validating. This is just how setting a message in ActiveModel validations works. If you really want the validation to do what you want you could write something like:

validate :presence_of_price

private

def presence_of_price
errors.add(:price, "for #{self.name} can't be blank") if price.blank?
end

Fully custom validation error message with Rails

Now, the accepted way to set the humanized names and custom error messages is to use locales.

# config/locales/en.yml
en:
activerecord:
attributes:
user:
email: "E-mail address"
errors:
models:
user:
attributes:
email:
blank: "is required"

Now the humanized name and the presence validation message for the "email" attribute have been changed.

Validation messages can be set for a specific model+attribute, model, attribute, or globally.

Modify error messages for validation with an option

I found these tags in my app. One of those should work for you!

equal_to: must be equal to %{count}
greater_than: must be greater than %{count}
greater_than_or_equal_to: must be greater or equal to %{count}
less_than: must be less than %{count}
less_than_or_equal_to: must be less or equal than %{count}
too_long:
one: 'is to short (max than: 1 character)'
other: 'is to long (max than: %{count} characteres)'
too_short:
one: 'is to short (min: 1 character)'
other: 'is to short (min: %{count} characteres)'
wrong_length:
one: doesn't have the right length (1 character)
other: doesn't have the right length (%{count} characteres)
other_than: must be different than %{count}

Rails validation error messages, customizing the attribute name

Use localization to set the "English" name of your attribute. You can set both the singular and plural names:

en:
activerecord:
attributes:
product:
unit:
one: Unit price
other: Unit prices


Related Topics



Leave a reply



Submit