Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow only english,numeric and special chars in textbox using jquery or javascript?

I want to allow only English,numeric and special characters to be typed in my web page. i want to apply this thing using jquery or javascript. Actually my application is in 2 languages so for that i want to do this. I want to do the same thing with Arabic language too.. please help me. How can I do that?

like image 555
Ram Avatar asked Oct 17 '25 11:10

Ram


1 Answers

You can try the following code that uses JavaScript replace method. The replace method accepts a regex pattern and so you can define pretty much anything you want/don't want typed in the textbox:

<script type="text/javascript">

      $('#textboxID').bind('keyup blur',function() { 
            $(this).val($(this).val().replace(/[^A-Za-z0-9]/g,''))
        });

</script>

Here's the jsFiddle to try this out: http://jsfiddle.net/leniel/rtE54/


After a bit more thinking I implemented this code:

$("#mytextbox").on("keypress", function(event) {

    // Disallow anything not matching the regex pattern (A to Z uppercase, a to z lowercase, digits 0 to 9 and white space)
    // For more on JavaScript Regular Expressions, look here: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions
    var englishAlphabetDigitsAndWhiteSpace = /[A-Za-z0-9 ]/g;

    // Retrieving the key from the char code passed in event.which
    // For more info on even.which, look here: http://stackoverflow.com/q/3050984/114029
    var key = String.fromCharCode(event.which);

    //alert(event.keyCode);

    // For the keyCodes, look here: http://stackoverflow.com/a/3781360/114029
    // keyCode == 8  is backspace
    // keyCode == 37 is left arrow
    // keyCode == 39 is right arrow
    // englishAlphabetDigitsAndWhiteSpace.test(key) does the matching, that is, test the key just typed against the regex pattern
    if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39 || englishAlphabetDigitsAndWhiteSpace.test(key)) {
        return true;
    }

    // If we got this far, just return false because a disallowed key was typed.
    return false;
});

$('#mytextbox').on("paste",function(e)
{
    e.preventDefault();
});

You can read more about it here: JavaScript regex + jQuery to allow only English chars/letters in input textbox

like image 111
Leniel Maccaferri Avatar answered Oct 19 '25 23:10

Leniel Maccaferri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!