17

I have the following code which prevents user from entering space when the length is 0. Now, how can I prevent user from entering all special characters(anything other than a-z A-Z 0-9) when the length is 0?

$('#DivisionName').bind('keypress', function(e) {
    if($('#DivisionName').val().length == 0){
        if (e.which == 32){//space bar
            e.preventDefault();
        }
    }
}); 

This is my text box.

<input type="text" id="DivisionName" />
Bittu
  • 387
  • 2
  • 6
  • 13
  • any character other than a-z A-Z 0-9 – Bittu Sep 04 '13 at 08:33
  • You could use e regexp to check alphanumeric chars: [link][1] [1]: http://stackoverflow.com/questions/388996/regex-for-javascript-to-allow-only-alphanumeric – mauretto Sep 04 '13 at 08:36
  • 1
    Your approach has the benefit of being simple (you don't need to care about cursor position) but I suppose it doesn't prevent users from pasting arbitrary clipboard contents. It might be an issue or not, depending on your needs. – Álvaro González Sep 04 '13 at 08:41

3 Answers3

23

The letter and digit ranges are (inclusive):

  • 97 - 122 (a-z)
  • 65 - 90 (A-Z)
  • 48 - 57 (0-9)

This is what you compare e.which against.

if (e.which < 48 || 
    (e.which > 57 && e.which < 65) || 
    (e.which > 90 && e.which < 97) ||
    e.which > 122) {
    e.preventDefault();
}

Or, using inverse logic:

var valid = (e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122);
if (!valid) {
    e.preventDefault();
}

Update

Even so, you may still wish to validate the field contents as a whole using a regular expression:

if (/^[A-Z0-9]+$/i.test(value)) {
    // it looks okay now
}

Or fix the field by replacing the bad stuff:

var stripped = value.replace(/[^A-Z0-9]+/i, '');
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • 1
    Knowing you already have the comparison code, you just need simple modification. That in itself is a working example – Hanky Panky Sep 04 '13 at 08:38
  • 1
    I think sample code is a fair request. Not because the OP can't be bothered, but because it makes the answer more useful in the future – musefan Sep 04 '13 at 08:39
  • 1
    @Jack: Special characters are typed when we press "Shift" key. Can we alert the user when he presses shift key instead of checking all these conditions? – Anusha Honey Sep 04 '13 at 08:52
  • @AnushaHoney The passed event will also have a `shiftKey` property you can use to detect whether someone has pressed it. – Ja͢ck Sep 04 '13 at 08:59
  • Why not `'0'.charCodeAt(0)` etc., to make things more obvious? – KthProg Aug 05 '16 at 19:41
7

This is what you are looking for:

$('#DivisionName').bind('keypress', function(e) {

    if($('#DivisionName').val().length == 0){
        var k = e.which;
        var ok = k >= 65 && k <= 90 || // A-Z
            k >= 97 && k <= 122 || // a-z
            k >= 48 && k <= 57; // 0-9

        if (!ok){
            e.preventDefault();
        }
    }
}); 

or see here: http://jsfiddle.net/D4dcg/

Scheintod
  • 7,953
  • 9
  • 42
  • 61
  • 2
    shift + any letter followed by any number, while still pressing shift actually breaks this easily – mmln Jan 15 '15 at 04:55
-1

You can use a regex to validate the string. Something like ^[a-zA-z0-9].*

Here is an article about testing a regex in javascript : http://www.w3schools.com/jsref/jsref_regexp_test.asp

And you can even bind a change event and not a keypress.

Pavel Ronin
  • 576
  • 4
  • 11
  • The only problem is that he has a key press, not a string. If he switched his code to read the textarea content he'd need to implement stuff with text ranges to avoid random cursor jumps. – Álvaro González Sep 04 '13 at 08:39
  • You are absolutely right. In any case, this still looks like a case of a simple form validation.. – Pavel Ronin Sep 04 '13 at 08:41