Tom Tom - 1 year ago 68
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.


Answer Source


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download