how to reuse same set of validations on different columns and different models

Viewed 14

We have same set of validations on different fields. we have fee columns. with the following validations

validates :sytem_fee, presence: true, 
                      format: { with: fee_regex, message: format_error_message }, 
                      numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 40 }
validates :sytem_discounted_fee, presence: true, 
                                 format: { with: fee_regex, message: format_error_message }, 
                                 numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 40 }

The set of validations applied to the columns is basically the same. we have also the fees in different models. They have the same validations basicaly. I know that there are custom validators like: EmailValidator < ActiveModel::EachValidator

My question is: can we create a custom validator that uses the default validations like presence, numericallity and so on?

The idea is to be able to say validates some_fee, percent_fee_column: truein any model

1 Answers

You can put your method in the app/models/concerns folder, for example, as Validatable module (i.e. validatable.rb):

module Concerns::Validatable
  extend ActiveSupport::Concern

  def format_website
    if website.blank?
      self.website = nil
    elsif !self.website[/^https?/]
      self.website = "http://#{self.website}"
    end
  end

end

And then include it in each models as

include Concerns::Validatable
Related