1

I need to validate url, so I used site http://www.rubular.com/ and maybe I get wrong result. So I wrote this: w{3}\.[a-z]+\.[a-z]{3} in http://www.rubular.com/ and it gived me almost wanted result. In my model Website I wrote:

 VALID_URL_REGEX = /w{3}\.[a-z]+\.[a-z]{3}/
 validates :url, :presence => true, format: { with: VALID_URL_REGEX }

Question : how I can make to check, that last part should contain only 3 letters ?

Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
Denys Medynskyi
  • 2,353
  • 8
  • 39
  • 70
  • Why should the last part only contain 3 letters? This answer should give you a 'correct' regex. http://stackoverflow.com/a/1141962/79835 – row1 May 22 '12 at 08:16
  • 1
    It's wrong to check that the last part has only three letters. For instance, both `.eu` and `.info` are valid TLDs. – Mahmoud Al-Qudsi May 22 '12 at 08:16
  • Your regex has several problems. As others have said it only accepts 3 char tld. it doesn't take into account subdomains other than www, and fails to account for domains like wwww.history.uk.com, it also does not account for other chars which a domin name can have (e.g. - _). You would be better getting an existing regex that has been well tested. – Steve Robillard May 22 '12 at 08:22
  • 1
    When I'm doing VALID_URL_REGEX =(here code from [link](http://stackoverflow.com/a/1141962/79835) but I get error A regular expression or a proc or lambda must be supplied as :with. So how I should change this : validates :url, :presence => true, format: { with: VALID_URL_REGEX } ? – Denys Medynskyi May 22 '12 at 08:44

1 Answers1

1

You have to use \A and \z to match against start and end of string.

Like this: /\Aw{3}\.[a-z]+\.[a-z]{3}\z/.

But like Mahmoud Al-Qudsi said, tlds can have more or less than 3 letters. And you should make it match multiple subdomains or naked domains (e.g. stackoverflow.com instead of www.stackoverflow.com).

I came up with this /\A(?:[\w-]+(?<!-)\.){1,}[\w]{2,}\z/.

lukad
  • 17,287
  • 3
  • 36
  • 53
  • Thank u for help! When I'm doing VALID_URL_REGEX =(here code from [link](http://stackoverflow.com/a/1141962/79835) but I get error A regular expression or a proc or lambda must be supplied as :with. So how I should change this : validates :url, :presence => true, format: { with: VALID_URL_REGEX } ? – Denys Medynskyi May 22 '12 at 08:43
  • It's to long for comment, I did it like this: in my application made VALID_URL_REGEX = (the same text as in $search) – Denys Medynskyi May 22 '12 at 08:58