javascriptregexurl-validation

JS URL regex, allow only urls and empty string


I have the following regext:

var regex = /^(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g;

function test() {
    alert(regex.test(document.getElementById("myinput").value));
}

I want to allow url or empty string. regex solution please
How do I allow empty in this case?
https://jsfiddle.net/6kptovwc/2/
Thanks


Solution

  • Add an alternation with empty string (I've simplified a bit your regex):

    ^((?:https?:\/\/)?(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b[-a-zA-Z0-9@:%_\+.~#?&\/=]*|)$
    

    or

    ^((?:https?:\/\/)?(?:www\.)?[-\w@:%.+~#=]{2,256}\.[a-z]{2,6}\b[-\w@:%+.~#?&\/=]*|)$
    

    Demo & explanation