view raw
Tom Tom - 8 months ago 33
jQuery Question

Jquery Validate String - only allowing numbers and specific characters

How do I validate a string to only allow numbers and * and # ?

Currently I've got..

$('body').on('keyup', 'input', function(){
var str = $(this).val();

I'd like to say if str contains anything other that

My mind has gone blank on how to do this..

The validation should only allow numbers and * and # or a blank entry.

it doesn't matter the order if an invalid character appears anywhere in the string it should error.




var reg = new RegExp('^[0-9*#]+$'); 
if (str.trim() !="" && !reg.test(str)) {

change str.trim() !="" to $.trim(str) !="" for jQuery