diff options
author | Zeger-Jan van de Weg <mail@zjvandeweg.nl> | 2015-12-10 16:27:26 +0100 |
---|---|---|
committer | Zeger-Jan van de Weg <mail@zjvandeweg.nl> | 2015-12-10 16:27:26 +0100 |
commit | 82d2e5c3c561f213a59c1df36c6d5c4bb2eef7d0 (patch) | |
tree | 0e6e0efcc6dc6ff1b517c82fb3b2a86cf78e8e4f /app/validators/url_validator.rb | |
parent | 5fd280f3d3264aec3656cb61cd8728f2ca4d61ce (diff) | |
parent | 4e5897f51ef97d7c3ff6c57f81521f552979a3da (diff) | |
download | gitlab-ce-82d2e5c3c561f213a59c1df36c6d5c4bb2eef7d0.tar.gz |
Merge branch 'master' into copying-file-seen-as-licence
Diffstat (limited to 'app/validators/url_validator.rb')
-rw-r--r-- | app/validators/url_validator.rb | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/app/validators/url_validator.rb b/app/validators/url_validator.rb new file mode 100644 index 00000000000..2848b9cd33d --- /dev/null +++ b/app/validators/url_validator.rb @@ -0,0 +1,36 @@ +# UrlValidator +# +# Custom validator for URLs. +# +# By default, only URLs for the HTTP(S) protocols will be considered valid. +# Provide a `:protocols` option to configure accepted protocols. +# +# Example: +# +# class User < ActiveRecord::Base +# validates :personal_url, url: true +# +# validates :ftp_url, url: { protocols: %w(ftp) } +# +# validates :git_url, url: { protocols: %w(http https ssh git) } +# end +# +class UrlValidator < ActiveModel::EachValidator + def validate_each(record, attribute, value) + unless valid_url?(value) + record.errors.add(attribute, "must be a valid URL") + end + end + + private + + def default_options + @default_options ||= { protocols: %w(http https) } + end + + def valid_url?(value) + options = default_options.merge(self.options) + + value =~ /\A#{URI.regexp(options[:protocols])}\z/ + end +end |