jQuery textbox validation using both on keyup and blur
jquery, validation
Solution
Thanks for all of your input. Some good ideas helped towards a solution. Sticking to topic from avoiding the display of two alerts using .on keypress and blur, here is what I ended up doing.
var bAlertCalled = false;
$("#txtLength").on('keyup blur', function (e) {
if (bAlertCalled === true) {
bAlertCalled = false;
return;
}
if ($(this).val().length > 0) {
var iLength = parseInt($(this).val());
switch (true) {
case !$.isNumeric($(this).val()):
bAlertCalled = true;
$(this).focus();
alert("Please enter a numeric value.");
break
case (iLength < 5) || (iLength > 10):
bAlertCalled = true;
$(this).focus();
alert("Length must be a numeric value between 5 and 10.");
break;
default:
}
}
});
Problem
I have a textbox and need to validate on both keyup and blur events. If I type in "X", both events will fire and obviously you will see two alerts based on the code below. The keyup event is needed as I may trigger some action based on a valid value and also need keep the blur event in case the Tab key is pressed. The goal is to display one alert here. \m/ \m/ ``` $("#txtLength").on('keyup blur', function (e) { if ($(this).val().length > 0) { switch (true) { case !$.isNumeric($(this).val()): alert("Please enter a numeric value."); $(this).focus(); break case ($(this).val() < 5) || ($(this).val() > 10): alert("Length must be a numeric value between 5 and 10."); $(this).focus(); break; default: } } }); ```