2

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?

ChatNoir
  • 415
  • 8
  • 18

3 Answers3

4

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:

Carlos Ramirez III
  • 7,314
  • 26
  • 33
0

You don't need to nest the message in an inner hash. The syntax for messages on validations is:

attribute :name, validate: true

Not very elegant, but you can set the error message manually:

contact = Contact.new
contact.valid?  # => false
contact.errors[:name] = "Can't be blank"  # => Will add "Can't be blank to the list of errors associated with  name"

Or, if you want to replace the original error:

contact.errors.set(:name, "Can't be blank")
Anthony E
  • 11,072
  • 2
  • 24
  • 44
0

If the above answers are not working (try them out first, rails is good with error messages) you could use JQuery to validate the fields before submit, there is a plugin for that https://jqueryvalidation.org/

From there site

    $("#myform").validate({
  submitHandler: function(form) {
    // some other code
    // maybe disabling submit button
    // then:
    $(form).submit();
  }
 });
Jon
  • 1,954
  • 1
  • 15
  • 13