I want to allow only English characters and numbers in HTML input field (A-Z, a-z, 0-9 are allowed). I don't want someone inserting special characters with copy/paste.
Allow only English characters and numbers in HTML input field
Asked Answered
#1996021 –
Executor
possible duplicate of How to allow only numeric (0-9) in HTML inputbox using jQuery? –
Bistre
If you are using new browser you can use pattern
attribute like
<input type="text" pattern="[A-Za-z0-9]" required/>
or you can use js like
$("#id").keypress(function(event){
var ew = event.which;
if(48 <= ew && ew <= 57)
return true;
if(65 <= ew && ew <= 90)
return true;
if(97 <= ew && ew <= 122)
return true;
return false;
});
Check this pattern="^[\x20-\x7F]+$
"
At me this it work:D
<input type="text" pattern="^[\x20-\x7F]+$" >
In JavaScript, create a conditional checking for ASCII values. A way to do this is
var character
will represent one character of the array of characters entered into the input field.
character.charCodeAt(0);
will turn it into an ASCII value. Then just use < than and > than symbols to check if the ASCII values are in range of letters and numbers.
The pattern
attribute did not work for me. The following did work however.
HTML:
<input oninput="doOnInput()">
JavaScript:
function doOnInput()
{
// That's the only solution that worked to filter pastes and emojis
// Remove invalid chars from our value
let value = event.currentTarget.value;
let fixedValue = "";
for (const c of value) {
let code = c.charCodeAt(0);
if (( code >= 0x20 && code <0x7F)) {
fixedValue = fixedValue + c;
}
}
// Apply changes if chars were removed
if (value!=fixedValue) {
event.currentTarget.value = fixedValue;
}
}
© 2022 - 2025 — McMap. All rights reserved.