locked
Allow only these charaters in javascript or jquery RRS feed

  • Question

  • User-1165293366 posted

    Allow only these characters in textbox and restrict other characters from being inserted 

    Allow only 
    alphabets , numbers , left key, right key, backspace key, delete key, forward slash, round brackets (), ampersand, dot, dash, whitespaces 

    other characters should be ignored.

    Thursday, May 10, 2018 3:35 PM

All replies

  • User-284744251 posted

    Get keycode/ascii code for each key you want to allow, and handle onkeypress event where you can check for key press. Following link contains example

    https://www.cambiaresearch.com/articles/39/how-can-i-use-javascript-to-allow-only-numbers-to-be-entered-in-a-textbox

    Thursday, May 10, 2018 4:49 PM
  • User61956409 posted

    Hi spidergrey.emad,

    You can put these key codes in an array, then you can check if keyCode of current pressed key is in that array. The following code logic would help you achieve the requirement, you can refer to it and complete it by yourself.

    $("input[type='text']").keydown(function (event) {
        //alphabets 65-90
        //numbers 48-57 and 96-105
        //left arrow	37
        //right arrow	39
        //backspace	8
        //delete	46
    
        //forward slash 191
    
        //shift	16
        //round brackets (), 
        //ampersand,
    
        //period 190
        //dash 189
        //whitespaces32
    
        var keycodes = [8, 16, 32, 37, 39, 46, 48, 49, 50, 51......];
    
        var kc = event.keyCode;
    
        if (keycodes.indexOf(kc) < 0) {
            //your code logic
            event.preventDefault();
        }
    
    });
    
    $("input[type='text']").keyup(function () {
        //get the value of the input box 
        //if it contains ! @ # $ etc, remove it
    
        //or you can use regular expression to replace ! @ # $ etc with "".
    })
    

    With Regards,

    Fei Han

    Saturday, May 12, 2018 5:24 AM