pixelcandy
pixelcandy

Reputation: 109

Regex URL validation in Ruby

I have the following ruby code in a model:

if privacy_policy_link.match(/#{domain}($|\/$)/) errors.add(:privacy_policy_link, 'Link to a specific privacy policy page on your site instead of your homepage.') end

This worked until a user tried to save a privacy policy link that looked like this:

https://example.com/about-me/privacy-policy-for-example-com/

The goal is that I don't want them linking to their base homepage (example.com or www.example.com etc) for this privacy policy link (for some random, complicated reasons I won't go into). The link provided above should pass the matcher (meaning that because they are linking to a separate page on their site, it shouldn't be considered a match and they shouldn't see any errors when saving the form) - but because they reference their base domain in second half of the url, it comes up as a match.

I cannot, for the life of me, figure out how the correct regex on rubular to get this url to pass the matching algorithm. And of course I cannot just ask the user to rename their privacy policy link to remove the "com" from it at the end - because this: https://example.com/about-me/privacy-policy-for-example would pass. :)

I would be incredibly grateful for any assistance that could help me understand how to solve this problem!

Rubular link: http://rubular.com/r/G5OmYfzi6t

Upvotes: 3

Views: 977

Answers (1)

Nick Ellis
Nick Ellis

Reputation: 1077

Your issue is the . character is any character so it matched the - in example-com.

If you chain it to the beginning of the line it will match correctly without trying to escape the . in the domain.

if privacy_policy_link.match(%r{^(http[s]?://|)(www.)?#{domain}($|/$)})

Upvotes: 2

Related Questions