Restrict multiple URLs or Email id in the Input field with jQuery validation

Restrict multiple URLs in the Input field with jQuery validation

Sometimes we need to restrict users from submitting more than one URL in the HTML form. In that scenario, we can use the following jQuery code. We need to use RegEx expression and JavaScript match() function to match the pattern of input string. When input string gets matched then it compared with allowed variable in the code.

You can set, how many URLs can be used in textarea. If you will set 2 then it allows only 2 URLs in the textarea.

Create a textarea and submit button :

<textarea id="text" cols="30" rows="4"></textarea><br />
<button id="submit">Submit</button>

Add ajax library to run the jQuery code :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

Add jQuery code to validate the input string.

var allowed = 1; // how many times url can be allowed
var regex = /https?:\/\/[\-A-Za-z0-9+&@#\/%?=~_|$!:,.;]*/g; //match urls
//var regex = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}\b/ig; //match emails

$('#text').on('input', function() {
	var textArea = $(this).val().match(regex); // search string
	if(textArea && textArea.length > allowed){
		$('#submit').prop("disabled", true);
	}else{
		$('#submit').prop("disabled", false);
	}
});

Here we have validated the multiple URL. you can validate the multiple email id also, for email id you can find RegEx expression in the above code, just uncomment that and you can validate the multiple Email id.

Using different RegEx expression you can validate the other things like a number, particular string pattern, etc.

NOTE

  •  /g at the end of regular expression? it stands for “Global search” flag. it returns multiple matched records, without this you will only get last matched record.