I want to validate a URL in Rails using URI.Parse, by saying that the URL is valid as long as URI.parse does not raise URI::InvalidURIError. Is that a good idea? What URLs would pass this validation test?
1 Answer
Yes, it's a good idea if you plan to use those URLs in your app.
URI will prove the string is parseable into these parts: scheme, userinfo, host, port, registry, path, opaque, query, fragment.
URI handles these schemes:
- FTP, HTTP, HTTPS, LDAP, LDAPS, or MailTo
- or URI::Generic
http://www.ruby-doc.org/stdlib-1.9.3/libdoc/uri/rdoc/URI/Parser.html#method-i-parse
If you have other schemes, you can handle them yourself after the parse.
URI.parse works by calling URI.split, which uses two regular expressions:
- URI::ABS_URI for absolute URIs
- URI::REL_URI for relative URIs
You can look at these to see how they match. You can alter them too if you like.