ConfusedDeer
ConfusedDeer

Reputation: 3415

Javascript regex for url without http

How do I modify the regex below so that a url without 'http://', 'https://', 'ftp://', or 'mailto://' still comes back as valid? The REGEX is taken from validator.js

var url = 'www.test.com';
isURL(url);

function isURL(url) {
     var urlRegex = '^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$';
     var urlT = new RegExp(urlRegex, 'i');
     if(!(url.length < 2083 && urlT.test(url)))
     {
         alert("invalid url");
     }
     else
     {
         alert("valid url");
     }
}

Upvotes: 0

Views: 2469

Answers (2)

Karl Reid
Karl Reid

Reputation: 2217

If you're using validation.js, it seems to support an option to disable protocol matching:

isURL(str [, options]) - check if the string is an URL. options is an object which defaults to { protocols: ['http','https','ftp'], require_tld: true, require_protocol: false, require_host: true, require_valid_protocol: true, allow_underscores: false, host_whitelist: false, host_blacklist: false, allow_trailing_dot: false, allow_protocol_relative_urls: false }.

So you could just do :

var isUrl = validator.isUrl(url, {require_protocol:false, require_valid_protocol:false});

It looks like that is the default though, so maybe you're not using the library directly.

Upvotes: 1

Rahul
Rahul

Reputation: 2738

Weird requirement for validating URL.

But you can do it by making (?:(?:http|https|ftp)://) optional using ? like this (?:(?:http|https|ftp)://)?

Upvotes: 2

Related Questions