Tuesday, September 21, 2010
Sunday, September 5, 2010
The Ruby Way to do URL Validation
As we know, to do URL validation we can use regular expression such as:
After I read blog post from Michael Bleigh, I realized that there is a Ruby way to do URL validation. The secret is regexp method of URI module. It will regenerate a regular expression based on the protocol name parameter that you pass in. URI::regexp will return 0 if URL is valid and return nil if URL is not valid.
If you use Rails, URI::regexp can be plugged directly into your model validation.
Update:
This approach seems flawed. When pass "http://" =~ URI::regexp("http") it will returns 0 indicating the URL to be valid. So, I recommend to use the regular expression provided at the beginning of the post.
my_url =~ /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix
After I read blog post from Michael Bleigh, I realized that there is a Ruby way to do URL validation. The secret is regexp method of URI module. It will regenerate a regular expression based on the protocol name parameter that you pass in. URI::regexp will return 0 if URL is valid and return nil if URL is not valid.
require 'open-uri'
"http://google.com" =~ URI::regexp("ftp") # => nil
"http://google.com" =~ URI::regexp("http") # => 0
"google.com" =~ URI::regexp("ftp") # => nil
"google.com" =~ URI::regexp(%w(ftp http)) # => nil
"http://google.com" =~ URI::regexp(["ftp", "http", "https"]) # => 0
If you use Rails, URI::regexp can be plugged directly into your model validation.
class ExampleModel < ActiveRecord::Base validates_format_of :site, :with => URI::regexp(%w(http https)) endThank You Michael Bleigh for sharing this.
Update:
This approach seems flawed. When pass "http://" =~ URI::regexp("http") it will returns 0 indicating the URL to be valid. So, I recommend to use the regular expression provided at the beginning of the post.
"http://" =~ URI::regexp("http") # => 0
"http://" =~ /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix # => nil
Thanks to Losk, who points out in the comments below.
Subscribe to:
Posts (Atom)
Popular Posts
-
Update 2012-02-19: This tutorial has been tested using Rails 3.0.11. Source code is available on Github: https://github.com/kuntoaji/rails_...
-
What is ActiveAdmin? Active Admin is a Ruby on Rails plugin for generating administration sytle interfaces. The goals of this plugin are ea...
-
As we know, to do URL validation we can use regular expression such as: my_url =~ /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{...
-
Setelah beberapa waktu lalu saya membuat artikel bagaimana cara instalasi Ruby on Rails , ada beberapa tips dari saya untuk mempelajari Ruby...
-
I'm new to Sinatra and I want to use it together with Active Record and Will Paginate. After hours searching, I've finally found out to use ...