I am trying to validate the input from the users with regular expressions here is my codes
$('input[name="payment_rate"]').keyup(function(){
var data = $(this).val();
var regx = /^[0-9]+$/;
console.log( data + ' patt:'+ data.match(regx));
if( data.match(regx) ){
$('.amt_err').fadeOut('slow');
}
else{
$('.amt_err')
.text('only Numeric Digits(0 to 9) allowed!')
.css({'color':'#fff', 'background':'#990000', 'padding':'3px'});
}
});
here is the html part:
<input type='text' class="txtbox" name='payment_rate' size='8'> <span class="amt_err"></span>
i want only digits but my code is only working the first time. I mean if I type any comma or alpha character, the error shows. But if I remove the same with backslash and again type the comma or something other than digits the error is not shown, I don’t know where the bug is in my code??
Please help me to find out the bug..
The first time the regexp matches (i.e. the content is ‘valid’), the error message element is hidden with
.fadeOut(). On subsequent error, the message and css are modified, but the element is not made visible.The following works:
In addition, the error message is hidden on zero-length string (i.e. empty). Not sure if that is required, but I’m guessing it is. See http://jsbin.com/uhelir/edit#javascript,html
Also, have a look at http://www.zurb.com/playground/jquery-text-change-custom-event, a jQuery plugin that provides a ‘text-change’ event which is a nicer way to determine when a user has finished typing (and it won’t fire if the text hasn’t changed, reducing processing overhead).