Showing posts with label numbers. Show all posts
Showing posts with label numbers. Show all posts

JavaScript regex + jQuery to allow only English chars/letters in input textbox

Yesterday I answered this question at StackOverflow. The questioner wanted this:

How to allow only English, numeric and special chars in textbox using jQuery or JavaScript?

My answer was this:

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

It has a flaw because if you test it, you’ll see that every time a disallowed character is typed, the keyboard caret/text cursor goes to the end of the textbox. This is something that shouldn’t happen. Aristos mentioned something that I hadn’t tested: “the problem with your answer is that if you try to type something in the middle of the text, the cursor moves to the end.” He is absolutely right. You can test it below. Click the Result tab and type a digit like 7 or some other disallowed char in the middle of the textbox text to spot the problem:

OK – of course there must be a solution to this annoying problem and I couldn't miss the opportunity to play with it to find something that just works as expected. This answer by Ender helped me get there. The following code is what I came up with. I commented the code so it should be easy to understand what's going on:

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

    // Disallow anything not matching the regex pattern (A to Z uppercase, a to z lowercase and white space)
    // For more on JavaScript Regular Expressions, look here: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions
    var englishAlphabetAndWhiteSpace = /[A-Za-z ]/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
    // englishAlphabetAndWhiteSpace.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 || englishAlphabetAndWhiteSpace.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();
});

Try it below:

Now you can type in the middle of the text and the text cursor should maintain its position.

The above version allows accented chars like á, é, â, ê, etc…

Note also that there’s a new event handler function (paste) attached to the input textbox. This removes the possibility of user pasting text in the textbox.

If you want to allow numbers/digits or any other special characters, it’s just a matter of updating the regular expression pattern. For example: if you want to allow digits from 0 to 9, just use this regex pattern:

var englishAlphabetAndDigits = /[A-Za-z0-9 ]/g;

Full 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();
});

Here’s an updated jsFiddle that allows digits:

It’s really impressive what some small amount of JavaScript and jQuery code allows you to do on the client side. Actually if you care there are more comments than codez… Surprised smile

There’s no doubt JavaScript and JQuery will reign in the years to come.

About the code
As everything in software the above piece of code needs more testing. If you find a bug or some functionality that is missing, just leave a comment.

References
JavaScript Regular Expressions Guide by Mozzila.org