admin管理员组

文章数量:1429617

I am trying to validate a url where the "http:www" is optional, so the yahoo and needs to be valid url but using the following regex does not take utl3 to be valid one . How can I fix this ??

function checkUrlTest(url){
            var urlregex = new RegExp("^(https?:\/\/www\.)?(^(https?:\/\/www\.)[0-9A-Za-z]+\.+[a-z]{2,5})");

            return urlregex.test(url);
        }
        url3 = "yahoo";
        url4 = "www.yahoo";

        alert(checkUrlTest(url3));

I am trying to validate a url where the "http:www" is optional, so the yahoo. and http://www.yahoo. needs to be valid url but using the following regex does not take utl3 to be valid one . How can I fix this ??

function checkUrlTest(url){
            var urlregex = new RegExp("^(https?:\/\/www\.)?(^(https?:\/\/www\.)[0-9A-Za-z]+\.+[a-z]{2,5})");

            return urlregex.test(url);
        }
        url3 = "yahoo.";
        url4 = "www.yahoo.";

        alert(checkUrlTest(url3));
Share Improve this question asked Apr 25, 2013 at 10:10 Manish BasdeoManish Basdeo 6,27923 gold badges72 silver badges103 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 1

Working Demo http://jsfiddle/fy66p/

Solution reside here: Negative Lookahead: http://www.regular-expressions.info/lookaround.html#lookahead with the www case and you should get what you are looking for. Lemme know how it goes!

Hope it fits your needs :)

code

function checkUrlTest(url){

    // Try this
    var urlregex = new RegExp("^(?!www | www\.)[A-Za-z0-9_-]+\.+[A-Za-z0-9.\/%&=\?_:;-]+$")

            return urlregex.test(url);
        }
        url3 = "yahoo.";
        url4 = "www.yahoo.";

        alert('===> ' + checkUrlTest(url4) + '===> ' + checkUrlTest(url3));
(http://)?(www\.)?[A-Za-z0-9]+\.[a-z]{2,3}

In this regex, http://www.yahoo., http://yahoo. and www.yahoo. are all valid URLs

Just check it out. All problems will resolve.

var rgx = /^\s*(http\:\/\/)?([a-z\d\-]{1,63}\.)*[a-z\d\-]{1,255}\.[a-z]{2,6}\s*$/;
function validateUrl(value)
{
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(value);
}

if not try this:

(?i)\b((?:(?:[a-z][\w-]+:)?(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))

本文标签: javascriptValidating url with httpwww as optional using regexStack Overflow