nbucciarelli
nbucciarelli

Reputation: 460

Custom validation messages

I am having trouble getting a custom message while still getting the error classes on the fields in the form.

For example:

errors.add(:first_name, 'must not be blank')

When first name is blank, it adds the div of field_with_errors and a message of 'First name must not be blank' when failing to submit a form.

errors.add(:base, 'First name must not be blank')

Fails to highlight the fields, but allows a fully customizable message.

Is there any (simpler?) way to have rails add the class to the first_name field while also having a fully customizable message?

Upvotes: 0

Views: 247

Answers (1)

fx_
fx_

Reputation: 1932

You can customize the way your attribute displays by changing it in your I18n localization files (e.g. config/locales/en.yml) like so:

en:
  activerecord:
    attributes:
      model_name:
        first_name: "First Name Alternative"

Or, by overwriting ActiveRecord::Base#human_attribute_name, even to deliver a blank humanize for your attribute so it is not prefixed to the error.

Upvotes: 1

Related Questions