I would like to disable all symbols entry into an input field that are not associated with following: letters or numbers or spaces or ampersand symbol or full stop.
E.g. ALLOWED: A-Z, a-z, 0-9, &, ., and space is allowed.
NOT ALLOWED: Every other character e.g. ! @ # $ % ^ * ( ) - + = [ ] ; : ' " < > , / ? | = ` ~ etc.
<input id="ItemName" type="text" />
I would like to disable all symbols entry into an input field that are not associated with following: letters or numbers or spaces or ampersand symbol or full stop.
E.g. ALLOWED: A-Z, a-z, 0-9, &, ., and space is allowed.
NOT ALLOWED: Every other character e.g. ! @ # $ % ^ * ( ) - + = [ ] ; : ' " < > , / ? | = ` ~ etc.
<input id="ItemName" type="text" />
Share
Improve this question
edited Sep 3, 2015 at 0:33
royhowie
11.2k14 gold badges53 silver badges67 bronze badges
asked Sep 3, 2015 at 0:32
Kim TranKim Tran
2791 gold badge4 silver badges12 bronze badges
2
- What have you tried so far? – nnnnnn Commented Sep 3, 2015 at 0:35
-
1
is HTML5 OK? If so you can use a
pattern
attribute and give a simple regex. Something likepattern="[A-Za-z0-9& .]*"
– dmeglio Commented Sep 3, 2015 at 0:36
4 Answers
Reset to default 1You can register a keypress event handler and return false if you don't "like" the new input :
$('#ItemName').keypress(function (e) {
var txt = String.fromCharCode(e.which);
if (!txt.match(/[A-Za-z0-9&. ]/)) {
return false;
}
});
JSFiddle: http://jsfiddle/cgx1yqyf/
Note that this solution requires JQuery
The right way is using an "input" event.
document.addEventListener('input', script);
https://developer.mozilla/en-US/docs/Web/Events/input
Question is old, but it's never too late to answer
$(document).ready(function() {
//prevent paste
var usern_paste = document.getElementById('yourid');
usern_paste.onpaste = e => e.preventDefault();
//prevent copy
var usern_drop = document.getElementById('yourid');
usern_drop.ondrop = e => e.preventDefault();
$('#yourid').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z0-9\s]");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
});
Yes, yes, I know. This question is old. But I'd just give it a try (without jQuery)
HTML
<input type="text" placeholder="Try to put a non-alphabetical character here! (you can put a number and a space too)" id="nochars" />
JS
const input = document.getElementById("nochars"); // gets the element (the input) by it's id
input.addEventListener("input", (event) => {
const char = String.fromCharCode(event.keyCode)); // changes the keycode from a int to a string
if (!(/[a-zA-Z0-9\s\.$]/.test(char))) {
event.preventDefault(); // prevents the default (which is adding the character to the value)
}
});
Also, check on what EventTarget.addEventListener
does. (\s
is a whitespace - a space)