开发者

Custom validation messages

开发者 https://www.devze.com 2023-02-16 18:59 出处:网络
I am having trouble getting a custom message while still getting the error classes on the fields in the form.

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 nam开发者_如何学JAVAe 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消