Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent user from entering special characters in text box when length is 0?

Tags:

html

jquery

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" />
like image 202
Bittu Avatar asked Sep 04 '13 08:09

Bittu


People also ask

How do I restrict the input field of a character?

To set the maximum character limit in input field, we use <input> maxlength attribute. This attribute is used to specify the maximum number of characters enters into the <input> element. To set the minimum character limit in input field, we use <input> minlength attribute.


1 Answers

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, '');
like image 163
Ja͢ck Avatar answered Oct 21 '22 09:10

Ja͢ck