I found the HTTP URL Validator for Rails very interesting, and well coded, yet it lacked some things such as URL format restrictions. I added some things, and I came up with a sweet solution.
It checks the format of the given URL, the content type, and whether it was permanently moved. I might be adding to this in the future.
#Check for content type:
validates_http_url :url, :content_type => "text/html"
#Do not check for content type, just make sure the site is accessible:
validates_http_url :website
#Make sure there is a DNS entry for a domain
validates_http_domain :domain
# Domain must be in 'www.site.com' for or 'site.com' form.
# No http://, no path.
Update (6/26/06)
Added the validates_http_domain method:
def validates_http_domain(*attr_names)
validates_each(attr_names) do |record, attr_name, value|
# Set valid true on successful connect (all we need is one, one is all we need)
failed = true
possibilities = [value, "www."+value]
possibilities.each do |url|
begin
temp = Socket.gethostbyname(url)
rescue SocketError
next
end
failed = false
break
end
record.errors.add(attr_name, "cannot be resolved.") if failed
end
end
Now I can just use
:validates_http_domain :website
in my controller, and everything comes up roses. ;)
Update (9/30/06)
It was brought to my attention through a dialogue of emails and the comments that I needed a simple way for people to modify the plugin to accept different codes depending on their needs, or at least a simple way for me to modify the default accepted codes. Therefore, I made an array in the library called allowed_codes:
allowed_codes = [
Net::HTTPMovedPermanently,
Net::HTTPOK,
Net::HTTPCreated,
Net::HTTPAccepted,
Net::HTTPNonAuthoritativeInformation,
Net::HTTPPartialContent,
Net::HTTPFound,
Net::HTTPTemporaryRedirect,
Net::HTTPSeeOther
]
I’ll make it so you can push on your own custom codes from the model soon. This is what I envision:
validates_http_url :website, :extra_codes => [ HTTPResetContent, HTTPPartialContent ]
I’ll post here when this is reality, and probably make another blog post as well so the aggregators get it.
You can download it with svn:
svn co https://modzer0.cs.uaf.edu/repos/hank/code/http_url_validation_improved
Or use it as a plugin:
./script/plugin install -x https://modzer0.cs.uaf.edu/repos/hank/code/http_url_validation_improved
The above command only works if you have your entire rails project in subversion. If you do not, which I don’t recommend, you should either add it to a repository or alternatively remove the *-x* from the command. Of course, this will remove support for updating to the new code if I make a change.
Uncategorized
plugins, rails, ruby, validation