Allow only English characters and numbers in HTML input field
Asked Answered
Y

4

-1

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.

Yeasty answered 21/7, 2015 at 8:46 Comment(2)
#1996021Executor
possible duplicate of How to allow only numeric (0-9) in HTML inputbox using jQuery?Bistre
L
4

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;
});
Lesh answered 21/7, 2015 at 8:54 Comment(0)
R
2

Check this pattern="^[\x20-\x7F]+$" At me this it work:D

<input type="text" pattern="^[\x20-\x7F]+$" >
Rector answered 16/1, 2019 at 10:29 Comment(0)
W
0

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.

Waylay answered 21/7, 2015 at 8:54 Comment(0)
K
0

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;
    }
}
Kurtiskurtosis answered 5/9, 2024 at 18:18 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.