Wednesday, March 18, 2015

How to Validate Regular Expressions in Ruby on Rails Models

ActiveRecord has many awesome validators for common things like presence, numericality, etc. Unfortunately, it is missing one common format - regex, or regular expressions. These are normally saved as string fields and, if not validated, can lead to page errors when your app tries to use a field that contains an invalid regular expression. This is especially the case if you allow the user to input a regular expression. With the addition of one small validation class, you will be able to prevent these sorts of bugs with your models.

The above code adds a validator called RegularExpressionValidator to app/validators/regular_expression_validator.rb. It then adds the validation to the Bear model on the field my_regex_field. With this, if you try and create a Bear with an invalid regular expression, an error will be thrown and the save will not complete.

1 comment: