Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if given string is an URL

In my rails application I need to verify if the URL given by a user is really an URL. I'm only concerned with the HTTP protocol (and perhaps HTTPS, I have not looked into that at all), which leads me to believe that there might something already in rails that can do this work for me.

If not: can you recommend a regex string that does this? I've found some after googling but they all seem to have a problem or two according to user comments.

Thanks

like image 985
Emil Ahlbäck Avatar asked Mar 16 '11 19:03

Emil Ahlbäck


People also ask

How do you check if a string is a URL in Python?

To check whether the string entered is a valid URL or not we use the validators module in Python. When we pass the string to the method url() present in the module it returns true(if the string is URL) and ValidationFailure(func=url, …) if URL is invalid. Here is the code to validate a URL in Python.

How do you check if a string is a URL in C#?

Use the StartWith() method in C# to check for URL in a String.

How do you validate a URL?

When you create a URL input with the proper type value, url , you get automatic validation that the entered text is at least in the correct form to potentially be a legitimate URL. This can help avoid cases in which the user mis-types their web site's address, or provides an invalid one.

Are URLs strings?

A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters.


2 Answers

Use the URI library.

def uri?(string)   uri = URI.parse(string)   %w( http https ).include?(uri.scheme) rescue URI::BadURIError   false rescue URI::InvalidURIError   false end 

This is a very simple example. The advantage of using the URI library over a regular expression is that you can perform complex checks.

like image 128
Simone Carletti Avatar answered Sep 21 '22 21:09

Simone Carletti


validates :url, :format => URI::regexp(%w(http https))

like image 34
amit_saxena Avatar answered Sep 17 '22 21:09

amit_saxena