Paul Nelligan
Paul Nelligan

Reputation: 2005

Ruby regex for domain validation

I'm looking for a regex to validate my user's chosen domain, I.E. http://mysite.com/userdomain.

All I'm concerned with is that it allows the right characters.

Upvotes: 0

Views: 682

Answers (4)

LuisVM
LuisVM

Reputation: 2793

You can use Rubular to test your Regexps.

Upvotes: 1

Bert Goethals
Bert Goethals

Reputation: 7887

Well, a regex will help you a long way, but you might want to consider just parsing the URL.

def validate_url(url)
  uri = URI.parse(url)
  uri.class != URI::HTTP
rescue URI::InvalidURIError
  false
end

Alternatively Addressable::URI could be used instead of URI (suggested by @abe-voelker)

(source: http://actsasblog.wordpress.com/2006/10/16/url-validation-in-rubyrails/)

Upvotes: 5

Tim Snowhite
Tim Snowhite

Reputation: 3776

Are you trying to figure out whether the user is giving you a name that is valid as a folder in a url? (CGI.escape(some_folder_name) != some_folder_name would probably get you where you need for that.)


Or are you looking for Regexp.new(Regexp.escape(some_url_string))?

That generates a regexp which matches any instance of some_url_string.

Used like so:

user.domain = "http://mysite.com/userdomain" # or "mysite.com/userdomain"
incoming_domain = "http://mysite.com/userdomain/a_post"
users_domain_regexp = Regexp.new(Regexp.escape(user.domain))
if incoming_domain =~ users_domain_regexp
   puts "By George, we've done it!"
else
   puts "I'm sorry, but we're prejudiced against that url"
end
#=> "By George, we've done it!"

Upvotes: 0

Michael Kohl
Michael Kohl

Reputation: 66847

Just head over to Regex Lib and pick one you like (the link already points to a search for the type of regular expression you are looking for).

Upvotes: 0

Related Questions