Search code examples
ruby-on-railsrubycustom-validators

Custom Validation for format


I have a class Links. The class has these attributes

  1. Twitter
  2. Facebook
  3. Pinterest
  4. Quora

I want to write a validation that makes sure when a user inserts a link into a textbox it starts with http or https.

The validation works, but I have a an issue when the user does not insert a link at all. It still tries to run the validation on the empty attribute and raises the error. The below code is my attempt at checking for a empty attribute.

Here's my validation:

     class Links <  ActiveRecord::Base
     attr_accessible :facebook, :twitter, :quora, :pinterest

     validate :formatted_link

     def formatted_link
      links = %w(facebook twitter pinterest quora)
       if links.any? {|link| self[link].nil?}
         #Don't want it to do any validation if column is nil. 
         #Would like to drop column if user doesn't add a link.
       else
          validates_format_of links, :with => URI::regexp(%w(http https))
          errors.add(:base, "Your link must start with http or https.")
       end
    end

Reason:

If a user just submits "www.twitter.com/username" the url get's appended to my sites url "mydomain.com/page/www.twitter.com/username. Not sure why this is happening. If there is something else I could do to prevent this or something I am missing please let me know.

Thanks.


Solution

  • I think you're trying to do conditional validation in a roundabout way. Since you really just want to allow blanks, you can do it this way:

    class Link < ActiveRecord::Base
      Networks = [:facebook, :twitter, :quora, :pinterest]
      attr_accessible *Networks
    
      validates_format_of *Networks, :with => URI::regexp(%w(http https)), :allow_blank => true
    end