views:

1004

answers:

5

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.split(".")
  name = /(?:[A-Z0-9\-])+/.match(domain_name[0]).nil?
  tld = /(?:[A-Z]{2}|aero|ag|asia|at|be|biz|ca|cc|cn|com|de|edu|eu|fm|gov|gs|jobs|jp|in|info|me|mil|mobi|museum|ms|name|net|nu|nz|org|tc|tw|tv|uk|us|vg|ws)/.match(domain_name[1]).nil?
  if name == false or tld == false
    errors.add(:domain_name, 'Invalid domain name. Please only use names with letters (A-Z) and numbers (0-9).')
  end
end

This is what I have so far but it doesn't work. It lets bad URLs through without failing.

I don't know regex very well.

A: 

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.)

David Hedlund
A: 

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.

Dan Breen
+3  A: 

Stumbled on this:

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

FYI: Rubular is a fantastic resource for testing your Ruby regular expressions

Tate Johnson
A: 

I like this plugin for validating URLs: https://github.com/henrik/validates_url_format_of/tree

trevorturk
A: 

Thank you Tate.

I took what you had and modified it so that I could make the http:// or https:// optional:

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

kirk