Is is possible to use Craft's URL validation without http:// or https:// in the URL? Or use some sort of function / filter to conditionally add it to the URL if it is missing?

I'm posting a form using sprout forms. The form contains a field that is set to validate as url.
If you post this field without adding http:// or https:// it doesn't validate.
Is it possible to somehow to set the defaultScheme of an url field to http without changing the core Craft UrlValidator or Yii's CUrlValidator?

  • Do I get this right, you have a string like example.com that represents a URL but is without the http:// part?
    – carlcs
    Aug 26, 2014 at 14:42
  • I'm posting a form which has a website field. In sprout forms i've defined the validation of that form field to be url. However when i post the form, it requires the url to have http:// or https:// in it. I want users to be able to post example.com and either have it validated as being an url or automaticly have http:// prepended to it Aug 26, 2014 at 15:04

1 Answer 1


To conditionally add http:// to strings that don't begin with http:// or https://, use the Twig matches operator in a comparison.

To keep the syntax compact, I use a ternary operator within the set tag.

{# Set an example URL without `http://` #}
{% set url = 'example.com' %}

{# "Correct" the URL notation #}
{% set url = url matches '/^(https?:\\/\\/)/' ? url : 'http://' ~ url %}

{# Test output #}
{{ url }}


This is no full URL check in my regular expression, but you could simply work that in too. Pay attention to the escaping character \ that (currently) needs to be escaped itself, so you end up with \\ (it's wrong in the Twig docs).

  • Thank you for your answer, but unfortunatly it's not the answer i'm looking for. The input of a formfield should be changed on post, not on pageload. Normally the defaultSheme should automaticly prepend it, but for some reason this isn't working Aug 26, 2014 at 15:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.