user962902
user962902

Reputation:

jquery validate a URL WHILST being input

is it possible to check for a valid format url at the time the user is entering it in a textbox?

urls format can be:

barfly.com
http://barfly.com
https://barfly.com
www.barfly.com

its important that the tld (suffix) is real to avoid: http://barfly.boo

ill be revisiting the script periodically to take into account new tlds that become popular (like .tv, .mobi, .firm.in etc ...

my code so far is letting through partial matches like:

www.barf  
http://www.barf

I MUST match the entire URL, not just parts of it

My code so far is:

    $('#txtbxhost').live('input', function() {

    var inp = $("#txtbxhost").val();
    var urlregex = new RegExp("^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([0-9A-Za-z]+\.([a-z]+\.))");

    if ( urlregex.test(inp) ) 
    {
    // keep showing ok label
    } 
    else {
    // hide ok label
    }   
    })

Upvotes: 0

Views: 55

Answers (1)

user428517
user428517

Reputation: 4193

First, $.live has been deprecated as of jQuery 1.7, so if you've using 1.7 or later, use $.on instead.

For a better URL regex, try one of these: http://mathiasbynens.be/demo/url-regex. You might as well use diegoperini's, since it's the most accurate:

_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS

That may be overkill for what you're trying to do, though. Just pick one that you think will cover most of your use cases.

Upvotes: 1

Related Questions