0

I have been using jquery to capture the keydown event and validate the entered text for different cases like: characters only, alpha-numeric, characters and spaces etc.

Regex used: Characters with spaces: ^[a-zA-Z ]+$ Characters only: ^[a-zA-Z]+$ Alphanumerics: ^[a-zA-Z0-9]+$

This is how I am using the bind function:

        $('.chars_and_space_only').bind('keydown', function (event) {
        // http://stackoverflow.com/a/8833854/260665
        var eventCode = !event.charCode ? event.which : event.charCode;
        if((eventCode >= 37 && eventCode <= 40) ||  eventCode == 8 || eventCode == 9 || eventCode == 46) { // Left  / Right Arrow, Backspace, Delete keys
            return;
        }
        // http://stackoverflow.com/a/8833854/260665
        var regex = new RegExp("^[a-zA-Z ]+$");
        var key = String.fromCharCode(eventCode);
        if (!regex.test(key)) {
            event.preventDefault();
            return false;
        }
    });

All of above uses cases are working fine, however I have to now include characters, spaces, apostrophe and periods. So this is the method I have modified:

        $(".chars_space_dots_apostrophes_only").bind('keydown', function (event) {
        // http://stackoverflow.com/a/8833854/260665
        var eventCode = !event.charCode ? event.which : event.charCode;
        if((eventCode >= 37 && eventCode <= 40) ||  eventCode == 8 || eventCode == 9 || eventCode == 46) { // Left  / Right Arrow, Backspace, Delete keys
            return;
        }
        // http://stackoverflow.com/a/8833854/260665
        var regex = new RegExp("^[a-zA-Z '.]+$");
        var key = String.fromCharCode(eventCode);
        if (!regex.test(key)) {
            event.preventDefault();
            return false;
        }
    });

This, strangely doesn't seem to work. Here is the fiddle: https://jsfiddle.net/ugu8f4y3/

Regex used: ^[a-zA-Z '.]+$ Regex validator does validate this text for the above regex:

Hello. World's

But the text field in fiddle does not allow me to enter periods and apostrophes, is there something I am missing here?

Raj Pawan Gumdal
  • 7,390
  • 10
  • 60
  • 92

1 Answers1

1

The problem is with jquery and the keydown event. Replace it with keypress and you'll be good to go. You should also only need to check in which.

keydown and keyup are important for cases when you're concerned with the position of the key's physical location. In this case you want to know that the key was depressed and handle the resulting input. jquery will normalize the character codes differently.

Further information about the differences between keypress, keydown and key up.

Updated Fiddle

Matt Wielbut
  • 2,584
  • 25
  • 29