jquery - How do I allow user to enter only underscore, space, alphabets and numbers in textbox -


i have following jquery.

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

it accepts character except space when length 0. how allow user enter a-z a-z 0-9 _ , space(in between characters)?

why don't try in regex

/[^a-za-z0-9_\s]/ 

update: try

$(document).ready(function () {     $('#name').bind('keypress', function (e) {         // filter non-digits input value.         if ($('#name').val().length == 0) {             if (e.which == 32) { //space bar                 e.preventdefault();             }         } else {             $(this).val($(this).val().replace(/[^a-za-z0-9_\s]/, ''))         }     }); }); 

regexplained here

jsfiddle


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -