(versión en español)

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:

RUBY:
  1. def validate
  2.   if my_field =~ /html|http|onclick|onmouseover/
  3.     errors.add("my_field", "should not contain html, http, onclick or onmouseover.")
  4.   end
  5. 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:

RUBY:
  1. module ActiveRecord
  2.   module Validations
  3.     module ClassMethods
  4.       def validates_unlike(*attr_names)
  5.         configuration = { :message => ActiveRecord::Errors.default_error_messages[:invalid], :on => :save, :with => nil }
  6.         configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)
  7.  
  8.         raise(ArgumentError, "A regular expression must be supplied as the :with option of the configuration hash") unless configuration[:with].is_a?(Regexp)
  9.  
  10.         validates_each(attr_names, configuration) do |record, attr_name, value|
  11.           record.errors.add(attr_name, configuration[:message]) if value.to_s =~ configuration[:with]
  12.         end
  13.       end
  14.     end   
  15.   end
  16. end

This code is available as a rails plugin: validates_unlike-0.1.zip


3 Respuestas a “Rails - validates_unlike plugin : validate that an attribute doesn’t match against a RegExp”

  1. 1 Sam

    Thanks for this plug-in. It's hard to believe there isn't something like this in core.

  2. 2 Sam

    Edgar, I hope you don't mind but I put a fork of validates_unlike up on GitHub.

    The URL is http://github.com/sschroed/validates_unlike

    I can remove it if you like but I find this to be useful so I thought I'd expose it to more people on GitHub.

  3. 3 Edgar

    Thanks Sam !

Añade un Comentario





RSS feeds

Suscríbete a nuestros RSS Feeds