How to prevent users from entering invalid characters inside an input field

后端 未结 4 1937
孤街浪徒
孤街浪徒 2020-12-21 17:33

Given a text input field. How can I prevent users from entering spaces, and other other than letters numbers or dashes (-).

Alphanumerics only - \"The alphanumeric

4条回答
  •  無奈伤痛
    2020-12-21 18:00

    Though my answer is very late, but this may help for further readers/techie's. Who wants to implement a textbox to accepts with below condition.

    • should accept Alphabets.
    • should accept Numbers.
    • should not accept any special characters.

    Below is the code.

    $("input[name='txtExample'] ").focus(function (e) {
    		if (!(e.which != 8 && e.which != 0 && ((e.which >= 48 && e.which <= 57)  || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122) ))) {
    			event.preventDefault();
    		}
    	}).keyup(function (e) {
    		if (!(e.which != 8 && e.which != 0 && ((e.which >= 48 && e.which <= 57)  || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122) ))) {
    		event.preventDefault();
    			}
    	}).keypress(function (e) {
    		if (!(e.which != 8 && e.which != 0 && ((e.which >= 48 && e.which <= 57)  || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122) ))) {
    			event.preventDefault();
    		}
    	
    	});
    
    

    added with example.

提交回复
热议问题