Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding www to website urls during validation

Currently when adding a url via a form on my Rails app we have the following before_save and validation checks:

def smart_add_url_protocol
  if self.website?
    unless self.website[/\Ahttp:\/\//] || self.website[/\Ahttps:\/\//]
      self.website = "http://#{self.website}"
    end
  end
end

validates_format_of :website, :with => /^((http|https):\/\/)?[a-z0-9]+([-.]{1}[a-z0-9]+).[a-z]{2,5}(:[0-9]{1,5})?(\/.)?$/ix, :multiline => true

However, what this means is that if I type into the form field

testing.com

It tells me that the url is invalid and I'd have to put in

www.testing.com

for it to accept the url

I would like it to accept the url whether or not a user enters www or http.

Should I add something else to the smart_add_url_protocol to ensure this is added, or is this an issue with the validation?

Thanks

like image 671
tessad Avatar asked Sep 07 '15 02:09

tessad


1 Answers

There is a standard URI class which can be used for checking urls. In your case you need URI::regexp method. Using it your class can be rewritten like this:

before_validation :smart_url_correction
validate :website, :website_validation

def smart_url_correction
  if self.website.present?
    self.website = self.website.strip.downcase
    self.website = "http://#{self.website}" unless self.website =~ /^(http|https)/
  end
end

def website_validation
  if self.website.present?
    unless self.website =~ URI.regexp(['http','https'])
      self.errors.add(:website, 'illegal format')
    end
  end
end
like image 145
dimakura Avatar answered Nov 09 '22 16:11

dimakura