Rails - validates_unlike plugin : validate that an attribute doesn’t match against a RegExp
Publicado por Edgar González 11 Julio 2006 en Rails, Ruby. english • españolWorking 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
This code is available as a rails plugin: validates_unlike-0.1.zip
Thanks for this plug-in. It's hard to believe there isn't something like this in core.
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.
Thanks Sam !