Is a URL starting with // valid?

Viewed 10972

We can see many HTML page using src="//example.com/myjavascript.js" to include a .js and let the browser use http:// / https:// depending on the current scheme of the page URL.

Is this a valid URI ?

3 Answers

It is valid indeed and I have just learned this in the hard way!! We broke a customization feature so you should always validate an URL like this (in .NET): Pay attention to:

  • White spaces (Trim)
  • "scheme relative" URI (UriKind.RelativeOrAbsolute)

    public bool IsValidUrl(string resourceUrl)
    {
        Uri uri;
        if (Uri.TryCreate(resourceUrl.Trim(), UriKind.RelativeOrAbsolute, out uri))
        {
            return uri.IsWellFormedOriginalString();
        }
    
        return false;
    }
    
Related