lundi 27 avril 2015

how to optimize repeated if/else blocks?

This is a fragment of validation code on an onSubmit event:

/**
 * ensure user name was provided:
 */
if (user_name.val() === '') {

    // display error on the name element 
    user_name.parent().addClass('error');
    user_name.parent().find('.error_msg').html('Name is required.');
    error = true;

} else {

    // reset error state
    user_name.parent().removeClass('error');
    user_name.parent().find('.error_msg').empty();

}

/**
 * Ensure user email was provided:
 */
if (user_email.val() === '') {

    // display error on the email element
    user_email.parent().addClass('error');
    user_email.parent().find('.error_msg').html('Email is required.');

} else {

    // reset error state 
    user_email.parent().removeClass('error');
    user_email.parent().find('.error_msg').empty();

}

/**
 * Ensure Message Subject was provided 
 */
if (message_subject.val() === '') {

    // display error on the subject element
    message_subject.parent().addClass('error');
    message_subject.parent().find('.error_msg').html('Message subject is required.');

} else {

    message_subject.parent().removeClass('error');
    message_subject.parent().find('.error_msg').empty();

}

/**
 * Ensure Message Body was provided
 */
if (message_body.val() === '') {

    // display error on the message body element
    message_body.parent().addClass('error');
    message_body.parent().find('.error_msg').html('A message is required.');

} else {

    message_body.parent().removeClass('error');
    message_body.parent().find('.error_msg').empty();

}

As you can see, lots of repeated if/else blocks with simple logic.

What would be a good way to optimize this code to reduce overall size while still accomplishing the same behaviors?

Aucun commentaire:

Enregistrer un commentaire