LoginSignup
5
3

More than 5 years have passed since last update.

gem validates_url 使ってみた

Last updated at Posted at 2015-09-15

validates_url という gem を使ってみました

名前のとおり URL のバリデーションをしてくれる gem で、custom validator で実装してたのを簡単にしてくれます

install

# add this to your Gemfile
gem "validate_url"

使い方

class User < ActiveRecord::Base

  validates :homepage, url: { allow_blank: true }

end

どんなチェックをしてるか見てみた

  uri = Addressable::URI.parse(value)
  unless uri && uri.host && schemes.include?(uri.scheme) && (!options.fetch(:no_local) || uri.host.include?('.'))
  • UIR.parse できること
  • host があること
  • scheme(http or https)を含むことを含むこと
  • オプションの no_local 指定がある場合、host に . を含むこと

バリデーションエラーはデフォルトで [属性名] is not valid url となってますが、I18n 対応で変更できます

参考

5
3
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
5
3