class EmailFormatValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i
object.errors[attribute] << (options[:message] || ‘is not valid’)
end
end
end
class EmailFormatValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i
object.errors[attribute] = “Maybe your email is malformed.”
end
end
end
But it is always prefixing the field name in the error:
Which exact code are you using to “show” the error message?
Internally, the error message is only remembered as “is not valid” or
“can’t be blank” (without the attribute name, as you want to have),
but certain forms of showing the error (related to the “full_message”
function of ActiveModel errors.rb) join it by default with the attribute
name:
E.g.
$ rails c
Loading development environment (Rails 3.2.1)
1.9.3p0 :001 > o = Order.new
1.9.3p0 :002 > o.valid?
=> false
1.9.3p0 :004 > o.errors[:name]
=> [“can’t be blank”]
1.9.3p0 :005 > o.errors.full_messages
=> [“Name can’t be blank” …]
1.9.3p0 :007 > o.errors.full_messages[0]
=> “Name can’t be blank”
So, if you simply used user.errors[attribute], you would get the
error message without the attribute prepended.
If you want to have the list of all of them, code like this might help
1.9.3p0 :011 > o.errors.map{|attr, message| message}.join(‘ ’)
=> "can’t be blank can’t be blank … "
Using I18n can resolve the problem in two ways:
…/config/locales$ cat errors.yml
en:
errors:
# The default format to use in full error messages.
# format: “%{attribute} %{message}”
format: “%{message}”
activerecord:
errors:
models:
order:
attributes:
name:
blank: Please fill in the name for this order
$ rails c
Loading development environment (Rails 3.2.1)
1.9.3p0 :001 > o = Order.new
1.9.3p0 :002 > o.valid?
=> false
1.9.3p0 :003 > o.errors.full_messages
=> [“Please fill in the name for this order”, “can’t be blank”, …]
I have changed 2 things here:
the error message itself for the Order#name attribute for a :blank
condition is customized.
the default “errors.format” that is used to form the “full_message”
string is changed to only have the error message (not prepended with
the attribute).
class EmailFormatValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i
object.errors[attribute] << (options[:message] || ‘is not valid’)
end
end
end
…
When email is invalid, this is the error shown:
Email is not valid
How can I customize theentire string?
I have tried this way in the custom validator:
…
object.errors[attribute] = “Maybe your email is malformed.”
Note the difference in the technique you’re using to alter
object.errors[attribute] in each case. Try mimicking the original way
more closely. Let us know if that works.