Dawid van der Hoven Dawid van der Hoven - 7 months ago 22
Javascript Question

jQuery shortening validation code

this is not so much a problem as just asking for advice, I'm busy studying JavaScript and jQuery, but I'm sure there's a way to shorten this:

//Validate General
$(document).on('blur keyup', 'input.main_name', function(e) {
if ($(this).val().length == 0) {
console.log('no main name');
}
});

$(document).on('blur keyup', 'input.main_surname', function(e) {
if ($(this).val().length == 0) {
console.log('no main surname');
}
});

$(document).on('blur keyup', 'input.main_town', function(e) {
if ($(this).val().length == 0) {
console.log('no main town');
}
});

$(document).on('blur keyup', 'input.main_email', function(e) {
if ($(this).val().length == 0) {
console.log('no main email');
}
});

$(document).on('blur keyup', 'input.main_postaladdress', function(e) {
if ($(this).val().length == 0) {
console.log('no main postal');
}
});

$(document).on('blur keyup', 'input.main_residential', function(e) {
if ($(this).val().length == 0) {
console.log('no main resi');
}
});

$(document).on('blur keyup', 'input.name', function(e) {
if ($(this).val().length == 0) {
console.log('no name');
}
});

$(document).on('blur keyup', 'input.surname', function(e) {
if ($(this).val().length == 0) {
console.log('no surname');
}
});

$(document).on('blur keyup', 'input.town', function(e) {
if ($(this).val().length == 0) {
console.log('no town');
}
});

$(document).on('blur keyup', 'input.email', function(e) {
if ($(this).val().length == 0) {
console.log('no email');
}
});

//Validate General


I just feel stupid copy and pasting, surely its not needed, the only reason, I did it this way is for unique error messages for each input...

Please can someone just educate me on this?

Thanks :)..

Answer

you could add the error message to the element like

<input type="text" data-msg="no name" class="name" />

then have

$(document).on('blur keyup', 'input', function(e) {
    if ($(this).val().length == 0) {
        console.log($(this).data('msg'));
    }
});