Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Regex url validation

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.

    function isUrlValid(userInput) {
        var regexQuery = "/(http(s)?://.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/";
        var url = new RegExp(regexQuery,"g");
        if (url.test(userInput)) {
            alert('Great, you entered an E-Mail-address');
            return true;
        }
        return false;
    }

I fix the problem by change the .test to .match and leave the regex as is.

like image 755
motis10 Avatar asked Jun 21 '15 22:06

motis10


People also ask

How do you check a URL is valid or not in JS?

You can use the URLConstructor to check if a string is a valid URL. URLConstructor ( new URL(url) ) returns a newly created URL object defined by the URL parameters. A JavaScript TypeError exception is thrown if the given URL is not valid.

How do I check if a Python URL is valid?

To check whether the string entered is a valid URL or not we use the validators module in Python. When we pass the string to the method url() present in the module it returns true(if the string is URL) and ValidationFailure(func=url, …) if URL is invalid.


1 Answers

I change the function to Match + make a change here with the slashes and its work: (http(s)?://.)

The fixed function:

function isUrlValid(userInput) {
    var res = userInput.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
    if(res == null)
        return false;
    else
        return true;
}
like image 145
motis10 Avatar answered Oct 11 '22 23:10

motis10