Dimitri de Ruiter Dimitri de Ruiter - 1 month ago 14
Ruby Question

Rails - check if field format is valid regex / catch RegexpErrors

In my app I store regex in a field (

value_regex
) - how can I check if the field contains a valid regex?

Is there a ruby function for it or a regex to do it?

Edit



Based on the input below, in my model
tag.rb
I have added:

validate :valid_regex


and the Method below (which I want to extend for another regex field
key_regex
too. First how to handle the exceptions/errors. I could not find documentation sofar:

def valid_regex
unless Regexp.new(value_regex)
errors.add(:value_regex, "not a valid regular expression")
end
end


Or easier

def valid_regex
@valid_regex ||= Regexp.new(self.value_regex)
end


How to catch the RegexpError(s) and output the message as an error (errors.ad?)?

Answer
@valid_value_regex ||= Regexp.new(self.value_regex)
rescue => exception
errors.add(:value_regex, exception)