Restrict multiple URLs in Input with jQuery

Sometimes we may want to restrict user from entering more than one URL or prevent entering same words in text input box, with jQuery it is very simple and this snippet below can come in handy in one of those situations.

multipal-url-validation

Here we use JavaScript match() method to search string in text input box. match() method returns any matched string as Array object, we will just count the number of matched strings and then notify user and disable submit button until the URL is reduced to one.

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$(document).ready(function() {
$('#description').bind('keyup', function() {
    var textArea = $(this).val().match(/http:\/\//g); // search for string
    var UrlNoAllowed = 1;
    if(textArea!==null && textArea.length> UrlNoAllowed) //check wheather it is NULL
    {
        $("#submit").attr("disabled", "disabled"); // disable submit button
        $("#error").html("Not allowed to enter more than 1 URL!"); //outpur error
    }else{
        $("#submit").removeAttr("disabled"); // restore submit button
        $("#error").html(""); //restore output error
    }
});    
});

Notice g modifier at the end of regular expression? that’s because without the g (global search), we will only get 1 match, and here we are searching for multiple string, thus the /g is required at the end.

Mark Up

As you can see in example below — we have a text box, submit button and div element for error output.

 
1
2
3
<div id="error"></div>
<textarea id="description" cols="40" rows="5"></textarea><br />
<input type="button" id="submit" value="submit">

Demo

Try entering multiple URL below, button should be disabled if it finds more than 1 URL and output the error.


Button

Related Articles:

Article by on March 3, 2013 Tagged under Tagged under . If you like this article, please consider sharing it.

Leave a Comment

Get your comment picture from Gravatar.com.
Your email address will not be published. Required fields are marked *