JSFiddle: https://jsfiddle.net/mqfntbws/
I have a contenteditable span
in which I want to prevent users from typing special characters or numbers. The problem is, I'm able to prevent special characters but it won't work on numbers. Anyone know what I'm doing wrong?
HTML:
<span required="" contenteditable="" placeholder="First Name" aria-required="true"></span>
JS:
$('span[contenteditable]').on('keypress', function (event) {
var regex = new RegExp("^[A-z]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key) && !((event.keyCode>=46 && event.keyCode<=58) || event.keyCode==8 || event.keyCode==9 || (event.keyCode>=37 && e.keyCode<=40))) {
console.log(">>>");
event.preventDefault();
return false;
}
});
As you appear to be using jQuery, you can make full use of the isNumeric()
function within the API.
From the documentation :
The $.isNumeric() method checks whether its argument represents a numeric value. If so, it returns true. Otherwise it returns false. The argument can be of any type.
So using this cleans up your if
statement immensely.
if(!regex.test(key) || $.isNumeric(key))
Leaving you with the following:
$('span[contenteditable]').on('keypress', function (event) {
var regex = new RegExp("^[A-z]+$");
var key = String.fromCharCode(event.which);
if (!regex.test(key) || $.isNumeric(key)) {
event.preventDefault();
return false;
}
});
I have forked and updated your original fiddle with a working example: https://jsfiddle.net/GH05T/mqfntbws/6/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.