Is there a standard regex validator for Rails?

I have a Rails model with an attribute that is a regular expression. Is there a standard way to verify that an attribute value is a valid regular expression before saving?

Update: According to the accepted answer, here is what I did:

class Foo < ActiveRecord::Base
  validates_each :bar do |model, attr, value|
    begin
      Regexp.compile value
    rescue RegexpError => e
      model.errors.add attr, "not a valid regular expression: #{e.message}"
    end
  end
  # [...]
end
+5
source share
1 answer

You can just ask Regexp.compileand catch the mistakes.

+4
source

All Articles