Wednesday, May 13, 2009

URL insertion validation in a Ruby on Rails form.

Hi !
I have been searching for a little bit how to make sure that when the user enters a URL in the URL field, the URL has a correct format.
I could have done it using JavaScript, but the idea was to use the controller instead.
So this is what I came up with.


class Comment < ActiveRecord::Base

belongs_to :post
validates_presence_of :nickname, :message => ": can not be blank."
validates_presence_of :content, :message => ": can not be blank."
validate :correct_url

protected
def correct_url
if website.length > 0 and !website.match(/^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix)
errors.add(:website, ": Please enter a valid URL (http://www.mysite.com).")
end
end
end


The correct_url function checks if the lenght of the field is > 0, means that the user inserted something, and then check if it matches the regular expression. If it doesn't,then we add a error message to the list of errors.

Hope this helps.
Martin





No comments:

Post a Comment