Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

URL Regex (See related posts)

// description of your code here
A regular expression pattern that validates a URL string, either HTTP or HTTPS.

/^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix


You can easily use it with validates_format_of in your Model...

For example, In a comment model, to check the :SiteURL on the comment creation:

class Comment < ActiveRecord::Base
    validates_format_of :SiteURL, :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix, :on => :create
end



Comments on this post

kwestion505 posts on Jul 12, 2007 at 15:29
I believe there is a mistake in the regex when matching urls that contain a port number.

this should fix it:

^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix


also what is the 5 letter domain extension you are including in the match?

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts