Tom Tom - 2 months ago 11
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
/[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

Answer

Try

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

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

Comments