开发者

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开发者_JAVA技巧 with is that it allows the right characters.


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/)


You can use Rubular to test your Regexps.


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).


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!"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜