I’m trying to use a regular expression to validate the format of a URL in my Rails model. I’ve tested the regex in Rubular with the URL http://trentscott.com and it matched.
Any idea why it fails validation when I test it in my Rails app (it says “name is invalid”).
Code:
url_regex = /^((http|https):\/\/)?[a-z0-9]+([-.]{1}[a-z0-9]+).[a-z]{2,5}(:[0-9]{1,5})?(\/.)?$/ix
validates :serial, :presence => true
validates :name, :presence => true,
:format => { :with => url_regex }
Your input ( http://trentscott.com) does not have a subdomain but the regex is checking for one.
Update
You also don’t need the ? after ((http|https):\/\/) unless the protocol is sometimes missing. I’ve also escaped . because that will match any character. I’m not sure what the grouping above is for, but here is a better version that supports dashes and groups by section