Validation: :if => ... does not work

Hi all

I’ve got the following model:

class Link < ActiveRecord::Base
attr_accessible :url,
:name,
:description,
:editors_pick,
:link_category_ids

validates_presence_of :url
validates_uniqueness_of :url
validates_length_of :url,
:maximum => 100
validates_format_of :url,
:with =>
/^(http|https)://[a-z0-9]+([-.]{1}[a-z0-9]+).[a-z]{2,5}(([0-9]{1,5})?/.)?$/ix,
:if => Proc.new { |link| !link.errors.on(:url) }

validates_presence_of :name
validates_uniqueness_of :name
validates_length_of :name,
:maximum => 40

has_and_belongs_to_many :link_categories,
:join_table => :links_are_categorized_by_link_categories

def before_validation
name.capitalize! if name # Capitalize name!
self.url = ‘http://’ + self.url if !self.url.empty? and self.url !~
/^http(s)?:///
end
end

I want only to check for the format of the url when there’s no other
error message for this attribute, so I added the :if => … statement:

validates_format_of :url,
:with =>
/^(http|https)://[a-z0-9]+([-.]{1}[a-z0-9]+).[a-z]{2,5}(([0-9]{1,5})?/.)?$/ix,
:if => Proc.new { |link| !link.errors.on(:url) }

Sadly this does not work: it displays both

* Url is invalid
* Url can't be blank

when leaving its field blank. :frowning: What’s going wrong here?

Thanks for help, Josh

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs