Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize error messages for validates numericality sub-options?

How can I customize the error messages for sub options when validating numericality on a field in an ActiveRecord model?

Example:

validates :month, :numericality => {
  :greater_than_or_equal_to => 1,
  :less_than_or_equal_to    => 12
}

In this case if the 'month' attribute is more than 12, I want to provide custom error message instead of the default "must be less than or equal to 12". How to achieve this?

like image 217
Vignesh Avatar asked Jun 12 '12 12:06

Vignesh


People also ask

What is custom error message?

Custom error pages enable you to customize the pages that display when an error occurs. This makes your website appear more professional and also prevents visitors from leaving your site.

Can we save an object in DB if its validations do not pass?

Some methods will trigger validations, but some will not. This means that it's possible to save an object in the database in an invalid state if you aren't careful.


1 Answers

If you don't want to use a custom validator, you could use the en.yml file instead. Assuming "post" was your model name, this provides examples for age-specific messages, post-specific messages, and generic (all models) messages.

en:
  activerecord:
    errors:
      models:
        post:
          attributes:
            age:
              less_than_or_equal_to: "Age-specific error" # Applies only to post.age
          less_than_or_equal_to: "Post-specific error" # Applies to all other fields for a post
      messages:
        less_than_or_equal_to: "Generic error" # Applies to all other models
like image 164
Dylan Markow Avatar answered Oct 19 '22 23:10

Dylan Markow