Tom
Tom

Reputation: 1628

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 /[0-9*#]/ alert('error')

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.

Thanks

Upvotes: 0

Views: 1251

Answers (1)

mplungjan
mplungjan

Reputation: 178422

Try

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

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

Upvotes: 1

Related Questions