Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery textbox validation using both on keyup and blur

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:
        }
    }
});
like image 558
80sRocker Avatar asked Jan 27 '14 17:01

80sRocker


1 Answers

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:
        }
    }
});
like image 53
80sRocker Avatar answered Oct 15 '22 03:10

80sRocker