Search code examples
ruby-on-railsruby-on-rails-4

How to add custom validation message on field name without field name as a prefix?


I am using

validates_presence_of :name, :message => "promo code required"

it gives

Name promo code required

I want only

promo code required

Solution

  • You could write a custom validation, and add the error message to the record as a whole, instead of a particular attribute as follows:

    validate :name_is_present
    
    private
    
    # Making this private is optional, but recommended
    def name_is_present
      errors.add(:base, "Promo code required") if name.blank?
    end
    

    For more details, refer to the explanation in Ruby guides here