|
| 1 | +# Validate if a value is a URI |
| 2 | +class UriValidator < ActiveModel::EachValidator |
| 3 | + def validate_each(record, attribute, value) |
| 4 | + if value.present? && not(valid?(value, options)) |
| 5 | + record.errors.add attribute, (options[:message] || "n'est pas un lien valide") |
| 6 | + end |
| 7 | + end |
| 8 | + |
| 9 | + private |
| 10 | + |
| 11 | + def valid?(value, options) |
| 12 | + # Valid links can be parsed by URI |
| 13 | + uri = URI.parse(value) |
| 14 | + |
| 15 | + # Authorize only given protocol |
| 16 | + if options.has_key?(:protocols) |
| 17 | + return options[:protocols].include?(uri.scheme) |
| 18 | + end |
| 19 | + |
| 20 | + # Links starting with "//MY_DOMAIN" are current scheme dependent and are valid |
| 21 | + return true if uri.scheme.nil? && uri.host == MY_DOMAIN |
| 22 | + |
| 23 | + # All other links are valid only if scheme and host exists |
| 24 | + return uri.scheme.present? && uri.host.present? |
| 25 | + rescue URI::InvalidURIError |
| 26 | + false |
| 27 | + end |
| 28 | + |
| 29 | + def self.before_validation(raw, default_scheme='http://') |
| 30 | + raw.strip! |
| 31 | + return nil if raw.blank? |
| 32 | + |
| 33 | + # Automatically encodes sharp signs (#) found in URI fragment: |
| 34 | + # RFC 3986 uses sharp to define URI fragment and requires other sharps |
| 35 | + # to be percent encoded |
| 36 | + fragments = raw.split("#") |
| 37 | + if (fragments.length > 2) |
| 38 | + raw = fragments[0] + '#' + fragments[1..-1].join('%23') |
| 39 | + end |
| 40 | + |
| 41 | + uri = URI.parse(raw) |
| 42 | + |
| 43 | + # If user forgot to add scheme, add default |
| 44 | + if default_scheme.present? && uri.scheme.blank? && uri.host.blank? |
| 45 | + raw = "#{default_scheme}#{raw}" |
| 46 | + uri = URI.parse(raw) |
| 47 | + end |
| 48 | + |
| 49 | + return uri.to_s |
| 50 | + |
| 51 | + # Let raw value if error occured when we tried to parse it, because |
| 52 | + # the HttpUrlValidator will manage it itself on validation |
| 53 | + rescue URI::InvalidURIError |
| 54 | + return raw |
| 55 | + end |
| 56 | + |
| 57 | +end |
0 commit comments