开发者

How can I customize rails3 validation error?

开发者 https://www.devze.com 2023-01-20 13:00 出处:网络
If I have a text input name \'email\', and if I set :message => \'Your email is wrong kind\' the validation error me开发者_C百科ssage will have something like

If I have a text input name 'email', and if I set :message => 'Your email is wrong kind' the validation error me开发者_C百科ssage will have something like

'Email Your email is wrong kind.'

I am wondering if there is any way to remove that orginal input name (in above case, its Email) from the validation error output in rails3.


There is probably a better way to do this, please let me know what it is, but this will work.

class User < ActiveRecord::Base
  validate do |user|
    user.errors.add_to_base("Your email is of the wrong kind") unless user.email =~ email_regexp
  end
end

An other hack-ish way to do this is to define a custom translation

# en.yml
en:
  activerecord:
    attributes:
      user:
        email: "Your email"

Combine this with :message => 'is wrong kind' and it should work. (although it's not really valid english ;) )


I think you can define your messages default format at you YAML file like this:

en: # Active Model errors: # The default format to use in full error messages. format: "%{attribute} %{message}"

Just remove the attribute part of the format.

0

精彩评论

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