1

I am using following code to allow only a-z, A-z, space, newline, tab.

But it doesn't allow tab key.

Here is my javascript code.

// Filter invalid characters in title
$('#p_title').keypress(function (e) {
        var regex = new RegExp("^[a-zA-Z0-9 \b\n\r\f\t\v]+$");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
                return true;
        }
        e.preventDefault();
        return false;
});
2
  • 1
    What do you mean by tab key? Commented Jul 4, 2015 at 10:52
  • The tab key which is just above "Caps Lock" key. Commented Jul 4, 2015 at 10:59

3 Answers 3

1

You need to double escape all escape sequences for constructing RegExp object. However better to just use regex literal in your case:

var regex = /^[a-zA-Z0-9 \b\n\r\f\t\v]+$/;

Full code:

$('#p_title').keypress(function (e) {
        var regex = /^[a-zA-Z0-9 \b\n\r\f\t\v]+$/;
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
           return true;
        }
        e.preventDefault();
        return false;
});
Sign up to request clarification or add additional context in comments.

Comments

1

Try use .on instead .keypress:

http://jsfiddle.net/z9wvfj1e/1/

// Filter invalid characters in title
$('#p_title').on('keydown', function (e) {
        if (e.keyCode >=37 && e.keyCode <=40) return true;
        var regex = new RegExp("^[a-zA-Z0-9 \b\n\r\f\t\v]+$");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
                console.log(e);
                return true;
        }
        e.preventDefault();
        return false;
});

1 Comment

Add simple check: if (e.keyCode >=37 && e.keyCode <=40) return true; [ jsfiddle.net/z9wvfj1e/3 ]
1

Something like this sounds like all you need:

$('#p_title').keypress(function (e) {
  return /[a-z]|\s|\r?\n|\t/i.test(String.fromCharCode(e.which));
});

I am doing a case-insensitive check for whether the character entered is a letter OR a space OR a newline OR a tab.

Furthermore, you don't need to check for e.charCode with jQuery because:

The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.

https://api.jquery.com/event.which/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.