I am trying to create a validation that checks to make sure a domain/url is valid for example \"test.com\"
def valid_domain_name?
domain_name = domain.spli
According to google, this one works nicely:
/^([a-z0-9]([-a-z0-9]*[a-z0-9])?\\.)+((a[cdefgilmnoqrstuwxz]|aero|arpa)|(b[abdefghijmnorstvwyz]|biz)|(c[acdfghiklmnorsuvxyz]|cat|com|coop)|d[ejkmoz]|(e[ceghrstu]|edu)|f[ijkmor]|(g[abdefghilmnpqrstuwy]|gov)|h[kmnrtu]|(i[delmnoqrst]|info|int)|(j[emop]|jobs)|k[eghimnprwyz]|l[abcikrstuvy]|(m[acdghklmnopqrstuvwxyz]|mil|mobi|museum)|(n[acefgilopruz]|name|net)|(om|org)|(p[aefghklmnrstwy]|pro)|qa|r[eouw]|s[abcdeghijklmnortvyz]|(t[cdfghjklmnoprtvwz]|travel)|u[agkmsyz]|v[aceginu]|w[fs]|y[etu]|z[amw])$/i
A bit lengthy...
It's case-insensitive...it doesn't look like your regexes are, but I don't know Ruby. Or maybe you capitalized them earlier.
^(http|https):\/\/|[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}(:[0-9]{1,5})?(\/.*)?$/ix
http://rubular.com/r/cdkLxAkTbk
Added optional http:// or https://
The longest TLD is .museum
, which has 6 characters...
Here is the regex used by henrik's validates_url_format_of Rails validator:
REGEXP = %r{
\A
https?:// # http:// or https://
([^\s:@]+:[^\s:@]*@)? # optional username:pw@
( ((#{ALNUM}+\.)*xn---*)?#{ALNUM}+([-.]#{ALNUM}+)*\.[a-z]{2,6}\.? | # domain (including Punycode/IDN)...
#{IPv4_PART}(\.#{IPv4_PART}){3} ) # or IPv4
(:\d{1,5})? # optional port
([/?]\S*)? # optional /whatever or ?whatever
\Z
}iux
This is my URL validator, using Ruby's built-in parser
class UrlValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
p = URI::Parser.new
valid = begin
p.parse(value)
true
rescue
false
end
unless valid
record.errors[attribute] << (options[:message] || "is an invalid URL")
end
end
end
What works for me is
def validate_url(text)
uri = URI.parse(text)
raise URI::InvalidURIError unless uri.kind_of?(URI::HTTP) || uri.kind_of?(URI::HTTPS)
rescue URI::InvalidURIError
errors.add(:url, 'is invalid')
end
end
Try adjusting the pattern so that they start with ^ (the "starts with" character), and ends with $ ("ends with"), so that the whole pattern reads "a string that starts with this and then ends", otherwise the match for name, say, will be a positive match if the pattern is found at all (i.e. has one single correct character.)