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
There is a standard URI class which can be used for checking url
s. 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With