Javascript – URL Validation for jQuery paste input

javascriptjquerypastevalidation

I'm trying to determine if a pasted URL is valid. I'm using the bind() function to detect a paste event. I'm using a regex that I found on here for the validation (which works and is fine for the time being). I'm also appending some text to tell the user if it's a valid url or not.

The only thing that isn't working when it's inside the bind() is the URL validation. It works when placed outside of it, though.

JS:

 function validateURL(textval) {
  var urlregex = new RegExp( "^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
  return urlregex.test(textval);
}

$(document).ready(function(){   

    // assign whatever is in the inputbox to a variable
    var url = $("#ent").val()

    //this is if they paste the url from somewhere
    $("#ent").bind('paste', function() {

        if(validateURL(url)) {
            $("#ent").css("background-color","green");
            $("#status").append("Valid URL");
            $("#submit").attr('disabled', 'disabled');
        }
    });

});

HTML:

<input type="text" name="ent" id="ent">
<input type="submit" name="submit" id="submit">
<div id="status"></div>

Best Solution

you can try this:

$(document).ready(function(){   
     function validateURL(textval) {
  var urlregex = new RegExp( "^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&amp;%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&amp;%\$#\=~_\-]+))*$");
  return urlregex.test(textval);
}
    // assign whatever is in the inputbox to a variable


    //this is if they paste the url from somewhere
    $("#ent").live('input paste', function() {
        var url = $("#ent").val();
        if(validateURL(url)) {
            $("#ent").css("background-color","green");
            $("#status").append("Valid URL");
            $("#submit").attr('disabled', 'disabled');
        }
    });

});

jsfiddle