Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize validation error message depending on the context

I need to have different error messages for the same model depending on the form's context and location.

For the User model which validates presence of first_name:

  • In the back-office page it is OK to have the validation message "First name can't be blank"
  • In the registration page the message should be "Please type your first name"

I am looking for a clean and best-practice oriented solution, because I would like not to hack with view helper and such.

Any hint appreciated, thanks

like image 406
Benj Avatar asked Jul 04 '26 06:07

Benj


2 Answers

You can use validate method in User model . Something like this

validate do |user|
 if user.first_name.blank? && user.id.blank? 
   # id blank means the user is in registration page as he is new user. 
   user.errors.add(:base, "Please type your first name")
 elsif user.first_name.blank?
   user.errors.add(:base, "First name can't be blank")
 end
end
like image 169
Paritosh Piplewar Avatar answered Jul 07 '26 08:07

Paritosh Piplewar


May be using hidden_field and attr_accessor, I hope you can achieve what you want,

Form 1:

<%= f.hidden_field :check_form, :value => true %>

Form 2:

<%= f.hidden_field :check_form, :value => false %>

You need to pass check_form value also to the model.

Model:

attr_accessor :check_form
validates_presence_of :first_name, :if => :check_form_is_true?, :message => "First Name can't be blank"
validates_presence_of :first_name, :unless => :check_form_is_true? //here you need to use i18n oriented translation to show the custom error message

private
def check_form_is_true?
  check_form == true
end

config/locales/en.yml

en:
  activerecord:
    attributes:
      user:
        first_name: ""
    errors:
      models:
        user:
          attributes:
            first_name:
              blank: "Please type your first name"

Hope it helps :)

like image 41
Rajesh Omanakuttan Avatar answered Jul 07 '26 09:07

Rajesh Omanakuttan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!