4

I have a field where the client can enter a URL, and then that field's value is put into the 'href' of a link in the template. The client will sometimes prepend it with "http://", sometimes with "www.", and sometimes with nothing. Unless it's prepended with "http://" or "https://", the link is interpreted as relative and tries to go to "http://mysite.com/www.otherlink.com", which is obviously not what I want.

What's the best way of automatically handling different URL formats?

shanecavaliere
  • 509
  • 1
  • 6
  • 14

2 Answers2

7

Using Craft, you could go two ways:

  1. Make your own field-type, that handles the url in PHP and appends http:// if needed (Create a plugin for that)

  2. Check the url for 'http' in your template, and if needed prepend it:

    {% set url = entry.url | slice(0,4) == 'http' ? entry.url : 'http://' ~ entry.url %}
    

Be sure to use the {% cache %} tag if you use option 2, so the check only has to be done once.

Edit: You could use this plugin to pre-validate your urls.

Paul
  • 6,338
  • 12
  • 26
3

There is a fieldtype called Link from Sprout that validates links, and it works very well.

One point of criticism is that the error it gives you when you haven't added the protocol isn't very client-friendly. It just says: 'Link must be a valid link.'

You could either contact Sprout and give them feedback on that, and they'll probably improve it (it's in beta), or you could modify it yourself.

Fred Carlsen
  • 2,997
  • 13
  • 23