jQuery Form Validation to Restrict Multiple URL

In jQuery, it is very simple to restrict user to enter more than one URL via a form input. By validating this, we can avoid spam content with more hyperlinks.

In previous tutorial, we have seen jQuery example to validate contact form. In this tutorial we are using jQuery match() to check the number of URL occurrences. For this jQuery function, we are passing a regex pattern to find URL match among input string.

jQuery-url-restrict

View DemoDownload

HTML Text-Area Input

This code shows HTML text-area input to the user. After entering text data, the jQuery regex match will be called to check URL occurrences.

<textarea id="text-content" cols="80" rows="4"></textarea>
<div>
	<input type="button" name="btnValidate" id="btnValidate" value="Submit" onClick="validate()"/>
	<label id="validation-message"></label>
</div>

jQuery URL Match

The jQuery regex match function will return the number of URLs entered by the user. We are checking for the URLs starts with http://, https:// or ftp://. If the count exceeds 1 then this code will return error message.

function validate() {
    var num_url_match = $('#text-content').val().toLowerCase().match(/(<a href="([^"]+)">([^$|\s+]*)<\/a>)/g); 	
	if(num_url_match.length > 1) {
        $("#validation-message").html(" More than 1 URL is not allowed.");
		$("#validation-message").css("color","#FF0000");
		$("#text-content").css("border-color","#FF0000");
    } else {
        $("#validation-message").html("");
		$("#validation-message").html(" " +num_url_match.length+ " URL is found.");
		$("#validation-message").css("color","#2FC332");
		$("#text-content").css("border-color","#F0F0F0");
    }
}

View DemoDownload

This jQuery code tutorial was published on December 28, 2014.

↑ Back to Top