Remove field name from object validation message

I have a simple check on the active record for an object using this in the form:

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

This in turn outputs something like "Field name of my user message"

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

Can someone point me in the right direction.

+7
ruby validation ruby-on-rails activerecord
source share
4 answers

One way to have full control over messages is to use your own validate block in the model. for example, to verify that the field is not empty, it will be as follows:

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

add_to_base designed to add messages that are not associated with a particular individual field (for example, if a combination of several fields is illegal). This means that CSS will not be added to highlight your invalid field. You can work around this by also adding a nil message to errors for your field, for example.

 model.errors.add(:field, nil) 

Alternatively, go to the custom-err-message plugin - this plugin allows you to not have your validation error message prefixed with the attribute name.

Update:

add_to_base deprecated with Rails 3. Instead, you can use the following: model_instance.errors.add(:base, "Msg")
Link: https://apidock.com/rails/ActiveRecord/Errors/add_to_base

+9
source share

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

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

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

+7
source share
+1
source share

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

0
source share

All Articles