简体   繁体   中英

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

您可以只询问Regexp.compile并捕获错误。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM