JS Regex url validation

后端 未结 4 535
梦毁少年i
梦毁少年i 2021-02-07 12:41

I tried to validate url with or without http No matter what i did the function return false. I checked my regex string in this site: http://regexr.com/ And its seen as i expect.

4条回答
  •  花落未央
    2021-02-07 12:56

    Try this code.

    function CheckURL(fieldId, alertMessage) {
        var url = fieldId.value;
        if(url !== "")
        {
            if (url.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g) !== null)
                return true;
            else {
                alert(alertMessage);
                fieldId.focus();
                return false;
            }
        }
    }
    
    var website = document.getElementById('Website');
    if (!CheckURL(website, "Enter a valid website address")) {
        return false;
    }
    

提交回复
热议问题