url validation in ruby on rails
1)Url field should also accept url as “www.abc.com”. If user enters url like this, it should be automatically appended with “http://” resulting in 开发者_JAVA技巧value saved in database as “http://www.abc.com”. If user enters url as “http://www.xyz.com” system should not append “http://”. User should be able to save url with “https://”. what is the code for it in ruby on rails?
This code worked:
def validate
if !self.external_url.blank? && self.external_url != "external url"
if self.external_url.match(/^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix).nil?
if self.external_url.match(/^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix).nil?
self.errors.add :base, 'External url is invalid' #message is changed by Hemant
else
self.external_url = "http://"+self.external_url
end
end
end
end
Not a great way to ask for assistance which is why I suspect you've been down voted twice!
I would suggest you start by looking at before_validation, validates_format_of and regular expressions. See how you get on with those and perhaps post any updates if you get stuck.
Ps:
prepend = "To attach to the beginning of data" append = "To attach to the end of the data"
精彩评论