Dimitri de Ruiter Dimitri de Ruiter - 1 year ago 117
Ruby Question

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

In my app I store regex in a field (

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

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


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

validate :valid_regex

and the Method below (which I want to extend for another regex field
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")

Or easier

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

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

Answer Source
@valid_value_regex ||= Regexp.new(self.value_regex)
rescue => exception
errors.add(:value_regex, exception)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download