Validates Unlike plugin

Plugin details

Validates that an attribute value doesn't match against the RegExp provided (just like validates_format_of, but with a negated condition)

Websitehttp://www.lacaraoscura.com/2006/07/11/validates-unlike-plugin/ Author Edgar González Tags validation LicenseUnknown

Documentation

This code is available as a rails plugin: validates_unlike-0.1.zip
http://www.lacaraoscura.com/wp-content/code/validates_unlike-0.1.zip

Working in rubycorner.com, I found myself needing to validate that a model attribute didn't match against some RegExp.

My first approach was to define a validate method in my model:

def validate
  if my_field =~ /html|http|onclick|onmouseover/
    errors.add("my_field", "should not contain html, http, onclick or onmouseover.")
  end
end


But this approach is not DRY, so I create a new method: validates_unlike, which just validates that an attribute value doesn't match against the RegExp provided (just like validates_format_of, but with a negated condition), the code is:

module ActiveRecord
  module Validations
    module ClassMethods
      def validates_unlike(*attr_names)
        configuration = { :message => ActiveRecord::Errors.default_error_messages[:invalid], :on => :save, :with => nil }
        configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)

        raise(ArgumentError, "A regular expression must be supplied as the :with option of the configuration hash") unless configuration[:with].is_a?(Regexp)

        validates_each(attr_names, configuration) do |record, attr_name, value|
          record.errors.add(attr_name, configuration[:message]) if value.to_s =~ configuration[:with]
        end
      end
    end   
  end
end

Further Documentation

There is currently no advanced documentation for this plugin.

New documentation

Edit plugin | Back in time (3 older versions) | Last edited by: hardway, about 1 year ago