开发者

Is there a standard regular expression validator for Rails?

开发者 https://www.devze.com 2023-03-03 17:40 出处:网络
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?

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


You could just ask Regexp.compile and catch errors.

0

精彩评论

暂无评论...
验证码 换一张
取 消