Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a standard regular expression validator for Rails?

I have a Rails model with an attribute that is a regular expression. Is there a standard way to validate that the attribute's value is a valid regexp before saving?

Update: As per the accepted answer, here's 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
like image 378
Josh Glover Avatar asked Oct 12 '22 02:10

Josh Glover


1 Answers

You could just ask Regexp.compile and catch errors.

like image 64
Christopher Creutzig Avatar answered Oct 14 '22 09:10

Christopher Creutzig