LoginSignup
7
2

More than 5 years have passed since last update.

【Rails】validates_format_ofを使ってformat指定を複数適応させる

Last updated at Posted at 2018-08-01

実現したいこと

すでにURIのformat指定をしていたわけだが、もう一つformat指定したいと思った。

validates :url, format: /\A#{URI::regexp(%w(http https))}\z/
#ここにもう一個urlのformatを指定したい

しかし、下にもう一個同じモデルでvalidationを立てればオーバーライドしてしまうだけで、実際に適応されるvalidationは一つのみになってしまう。

今回はこれを解決すべくいろいろ試してみた。

試したこと

ドキュメントをみるとvalidates_format_of というformに特化したメソッドがあり、オプションには
with ・・・ 正規表現を適応させるformat
without ・・・正規表現をかけたくないformat
とあった。

参考: http://railsdoc.com/references/validates_format_of

今回はドメイン名にbit.lyを含めたくないので、以下のようにオプションを指定。

validates_format_of :url, with: /\A#{URI::regexp(%w(http https))}\z/, 
                          without: /\A(http|https):\/\/bit.ly/  
Either :with or :without must be supplied (but not both)

しかし、どっちかにしろと怒られてしまった。。

これではbit.lyを含んだurlもしっかりパスしてしまう。

さらにbefore_validationで追加もしたがこれもダメ。

before_validation :sub_format

def sub_format
  url =~ /\A(http|https):\/\/[^bit.ly]/ 
end

バリデーションもう一個追加で解決

バリデーションをもう一個書いたらちゃんと両方ともバリデーションがかかりました。

validates_format_of :url, with: /\A#{URI::regexp(%w(http https))}\z/
validates_format_of :url, without: /\A(http|https):\/\/bit.ly/  

ここで注意したいのが、withoutで指定したほうは正規表現に含めたくないもの、すなわち否定系になることに気をつけていただきたい。

参考: https://stackoverflow.com/questions/19032445/validates-format-of-with-uriregexpwhttp-https-issue

7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2