summaryrefslogtreecommitdiff
path: root/app/validators/url_validator.rb
diff options
context:
space:
mode:
authorZeger-Jan van de Weg <mail@zjvandeweg.nl>2015-12-10 16:27:26 +0100
committerZeger-Jan van de Weg <mail@zjvandeweg.nl>2015-12-10 16:27:26 +0100
commit82d2e5c3c561f213a59c1df36c6d5c4bb2eef7d0 (patch)
tree0e6e0efcc6dc6ff1b517c82fb3b2a86cf78e8e4f /app/validators/url_validator.rb
parent5fd280f3d3264aec3656cb61cd8728f2ca4d61ce (diff)
parent4e5897f51ef97d7c3ff6c57f81521f552979a3da (diff)
downloadgitlab-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.rb36
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