jquery - How to prevent user from entering special characters in text box when length is 0? -
i have following code prevents user entering space when length 0. now, how can prevent user entering special characters(anything other a-z a-z 0-9) when length 0?
$('#divisionname').bind('keypress', function(e) { if($('#divisionname').val().length == 0){ if (e.which == 32){//space bar e.preventdefault(); } } });
this text box.
<input type="text" id="divisionname" />
the letter , digit ranges (inclusive):
- 97 - 122 (a-z)
- 65 - 90 (a-z)
- 48 - 57 (0-9)
this 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, may still wish validate field contents whole using regular expression:
if (/^[a-z0-9]+$/i.test(value)) { // looks okay }
or fix field replacing bad stuff:
var stripped = value.replace(/[^a-z0-9]+/i, '');
Comments
Post a Comment