简体   繁体   中英

Allow AlphaNumeric and other symbol using JavaScript

I have use this code for allow numeric only in textbox, but how make Charkey only allow AlphaNumeric and other symbol like -./ (dash,dot,slash)

this my code for allow Numeric

function NumericKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

thankyou

Firstly, Character Codes and Key Codes are different thing, what you're looking for is Key Codes .

You can first check the key codes you want to allow/disallow by looking them up in a online table, or here: http://keycode.info/

Then then by using a whitelist/blacklist to check the codes:

function NumericKey(evt){
    var allowed = [189, 190, 191]; // corresponds to **. , -**

    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return allowed.indexOf(charCode) >= 0;
    return true;
}

This would allow you to arbitrarily whitelist any keycodes.

A simpler solution to your case, since key codes of ,.- are adjacent to each other:

function NumericKey(evt){

    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode >= 189 && charCode <= 191))
        return false;
    return true;
}

You should not listen for keyboard events ( keydown / keypress / keyup ) to filter out certain characters, as the value of the input can also be updated by pasting or dropping text into it and there are many exceptions you should not prevent, such as arrows, delete, escape, shortcuts such as select all, copy, paste... so trying to come up with an exhaustive list of the ones that should be allowed is probably not a good idea.

Moreover, that won't work on mobile, where most keys emit the same values e.key = 'Unidentified' , e.which== 229 and e.keyCode = 229 .

Instead, just listen for the input event and update the input value removing all invalid characters while preserving the cursor's position:

 const input = document.getElementById('input'); input.oninput = (e) => { const cursorPosition = input.selectionStart - 1; const hasInvalidCharacters = input.value.match(/[^0-9 -./]/); if (!hasInvalidCharacters) return; // Replace all non-digits: input.value = input.value.replace(/[^0-9 -./]/g, ''); // Keep cursor position: input.setSelectionRange(cursorPosition, cursorPosition); };
 <input id="input" type="text" placeholder="Digits and - . / only" />

Here you can see a similar answer and example for a slightly more complex behaviour to allow only numbers with one single decimal separator: https://stackoverflow.com/a/64084513/3723993

Anyway, if you still want to try that approach, just keep in mind both e.which and e.keyCode are deprecated, so e.key or e.code should be used instead, which also makes the code easier to understand. Also keep in mind some old browsers used some non-standard codes for some keys, so, for example, left is usually 'LeftArrow' and right is 'RightArrow' , but on IE and Legacy Edge they would be 'Left' and 'Right' instead.

If you need to check KeyboardEvent's properties values such as e.key , e.code , e.which or e.keyCode you can use https://keyjs.dev . I will add information about these kinds of cross-browser incompatibilities soon!

Key.js \\ JavaScript KeyboardEvent 的键码和键标识符

Disclaimer: I'm the author.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM