Customizing Devise error messages in Rails 3?

后端 未结 3 1568
梦如初夏
梦如初夏 2020-12-03 00:14

I am using devise to handle authentication. Overall I like it, but I\'d like to customize the error display a bit. Right now I\'ve got the following in my view.



        
3条回答
  •  悲&欢浪女
    2020-12-03 00:48

    If you want to change the messages for the customs validations added by Device, check Christian's answer.

    Otherwise, if the validation you want to customize is a standard validation like email format, you don't need to remove the Devise validations and replace them with your own. A better way of handling this is to make use of the default error messages precedence listed in the Rails guides and override the error message for a particular field and a particular validation.

    For this particular question, the key that you need to add in config/locales/en.yml in order to change is invalid with a custom message for email errors is activerecord.errors.models.user.attributes.email.invalid (where user is the name of the model):

    en:
      activerecord:
        errors:
          models:
            user:
              attributes:
                email:
                  invalid: "custom invalid message"
    

    Rails will search for a message to show for a validation in the following order:

    activerecord.errors.models.[model_name].attributes.[attribute_name]
    activerecord.errors.models.[model_name]
    activerecord.errors.messages
    errors.attributes.[attribute_name]
    errors.messages
    

提交回复
热议问题