Thursday, 9 August 2007

validates percentage

So, we wanted to check that a user could enter both "20" and "20%" and "20.000%" and have them all perfectly valid for a field on our models. I finished up with this validation method (below) to add to ActiveRecord::Base.

  # validates whether the given object is a percentage
  # Can also take optional args which will get passed verbatim into the
  # "validates inclusion" method.
  # It will safely take the usual set of fields for that - but if you pass
  # in a new message - it will get used for both validations.
  # The default message is: "should be a percentage (0-100)"
  def self.validates_percentage(fields, args = {})
    msg = args[:message] || "should be a percentage (0-100)"
    validates_each fields do |model, attr, val|
       pre_val = model.send("#{attr}_before_type_cast".to_sym)
       unless val.nil? || !pre_val.is_a?(String) || pre_val =~ /^[-+]?\d+(\.\d*)?%?$/
         model.errors.add(attr, msg) 
    args[:message] = msg
    args[:in] = 0..100 
    validates_inclusion_of fields, args 

No comments: