perfectline / validates_url

URL Validation for Rails
MIT License
583 stars 113 forks source link

Allow "mailto:" urls #141

Closed gravitystorm closed 2 years ago

gravitystorm commented 2 years ago

I've been trying to figure out why mailto: urls are rejected by this gem. mailto: urls are slightly unusual since they only consist of a scheme and an opaque part (to use the RFC 2396 / RFC 3986 terminology).

> URI.parse('mailto:foo@example.com')
=> #<URI::MailTo mailto:foo@example.com>
> URI.split('mailto:foo@example.com')
=> ["mailto", nil, nil, nil, nil, nil, "foo@example.com", nil, nil]
> 'mailto:foo@example.com' =~ /\A#{URI::regexp(['mailto'])}\z/
=> 0
> URI.parse('mailto:foo@example.com').host
=> nil

Note that the host is nil, but the url is otherwise valid.

Our application considers http, https and mailto to all be valid for one particular attribute, so I'd like to use validates_url like this:

validates :url, :url => { :allow_nil => true, :schemes => %w[http https mailto] }

I think I've tracked it down to this line in the code:

https://github.com/perfectline/validates_url/blob/be6ce5284567f3ea09548a3766373aa1f697aa6a/lib/validate_url.rb#L58

This requires the host to be not nil, and was introduced in #18 .

I'm not sure what the right approach would be here to permit mailto: urls (and other schemes?) that don't require a host.

kritik commented 2 years ago

it's better to write own validator in this case

gravitystorm commented 2 years ago

Thanks @kritik for the quick response! It's not the answer that I was hoping for :smile: but I understand your position.