remove field name from object validation message

寵の児 提交于 2019-12-12 10:39:08

问题


I've got a simple active record validation on an object using this within a form:

  form.error_messages({:message => '', :header_message => ''})

This in turn outputs something like "FieldName My Custom message"

What i need to do is remove the field name from the error message but leave my custom message.

Can anyone point me in the right direction for this.


回答1:


One way to have complete control over the messages is to use a custom validate block in the model. e.g. to check that a field is not blank it would be like this:

class MyModel < ActiveRecord::Base
  validate do |model|
    model.errors.add_to_base("My Custom message") if user.field.blank?
  end
end

add_to_base is intended for adding messages that aren't related to a particular individual field (e.g. if a combination of multiple fields is illegal). This means that the CSS to highlight your invalid field won't get added. You can work arround this by also adding a nil message to the errors for your field e.g.

model.errors.add(:field, nil)

Alternatively, check out custom-err-message plugin - this plugin gives you the option to not have your custom validation error message prefixed with the attribute name.

Update:

add_to_base is deprecated since Rails 3. The following can be used instead: model_instance.errors.add(:base, "Msg")
Ref: https://apidock.com/rails/ActiveRecord/Errors/add_to_base




回答2:


In rails 3.2.6, you can set this in a locale file (e.g., config/locales/en.yml):

en:
  errors:
    format: "%{message}"

Otherwise, the default format is "%{attribute} %{message}".




回答3:


You can use errors.add_to_base http://api.rubyonrails.org/classes/ActiveRecord/Errors.html#M001712




回答4:


You can access the object's errors instance directly if you need full control over how the messages are presented.



来源:https://stackoverflow.com/questions/2951333/remove-field-name-from-object-validation-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!