Search code examples
ruby-on-railsvalidationmessagemail-form

Ruby on Rails: How to customise error message for MailForm when field is blank


At the moment, if I leave a field in the form blank, I get an error message that is written in the en.yml file, how can I overwrite this error message in the model?

class Contact < MailForm::Base
  attribute :name,      :validate => true
  attribute :email,     :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
  attribute :message,   :validate => true
  attribute :nickname,  :captcha  => true

This is what I've tried for the name attribute but I'm still getting the error message which is written in the en.yml file. I can't change the error message from en.yml as it is for another part of my application.

  validates :name, presence: { message: "Can't be blank" }

Any ideas why this is not overwriting the message?


Solution

  • You can customize the error message using i18n localization in the same way that you would for a regular ActiveRecord model. The only difference is that you use the mail_form top-level scope instead of active_record.

    # en.yml
    mail_form:
       errors:
          models:
             contact:
                attributes:
                   name: 
                      blank: "My custom message goes here"
    

    sources: