RealWorldDevelopers
7/7/2017 - 1:02 AM

JQuery Inputs AlphaNumeric Only

JQuery Inputs AlphaNumeric Only


$(document).ready(function(){
	$("input").keypress(function(e){
		return IsAlphaNumeric(e);
	});

	$("input").bind("paste", function(e){
		var element = this;
		setTimeout(function () {
			var text = $(element).val();
			// do something with text									
			alert(text);
			$(element).val(text.replace(/[^ a-zA-Z0-9]/g, ''));
		}, 100);						
	});

	$("input").bind("drop", function(e){
		var element = this;
		setTimeout(function () {
			var text = $(element).val();
			// do something with text									
			alert(text);
			$(element).val(text.replace(/[^ a-zA-Z0-9]/g, ''));
		}, 100);
	});						
});

var specialKeys = new Array();
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right
specialKeys.push(32); //(Space)

function IsAlphaNumeric(e) {
	var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
	var ret = ((keyCode == 32) ||                    // (Space)
		   (keyCode >= 48 && keyCode <= 57) ||   // numeric (0-9)
		   (keyCode >= 65 && keyCode <= 90) ||   // upper alpha (A-Z)
		   (keyCode >= 97 && keyCode <= 122) ||  // lower alpha (a-z)
		   (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
	document.getElementById("error").style.display = ret ? "none" : "inline";
	return ret;
}