dimanche 3 janvier 2016

What is wrong with this if/else Javascript function?

$('.chatterbox_comment_form').submit(function(e){
    e.preventDefault();

    var file        = $('#chatterbox_comment_file_upload_1')[0].files[0];
    var reader      = new FileReader();
    var white_space = /^\s+$/;
    var file_val    = $('#chatterbox_comment_file_upload_1').val();
    var exts        = ['jpg', 'jpeg', 'png', 'bmp', 'gif', 'svg'];

    if(!file) {

        if(comment_textarea.val() == '' || white_space.test(comment_textarea.val())) {  
            $('.chatterbox_comment_error').html("Can't be blank");
            comment_textarea.css('border', '1px solid #b20000');
        }
        else {
            socket.emit('chatterbox comment', comment_textarea.val(), user.name);
            $('.chatterbox_comment_error').html("");
            comment_textarea.css('border', '1px solid #ccc');
        }
    }
    else 
        if(file && comment_textarea.val()) {
            if(comment_textarea.val() == '' || white_space.test(comment_textarea.val())) {
                $('.chatterbox_comment_error').html("Can't be blank");
                comment_textarea.css('border', '1px solid #b20000');
            }
            else if(file_val) {
                var get_ext = file_val.split('.');

                get_ext = get_ext.reverse();

                if(!$.inArray(get_ext[0], exts) > -1) {
                    $('.chatterbox_comment_error').html('Only .jpg .png .bmp .gif .svg files are allowed');
                }
            }
            else {
                reader.onload  = function(evt) {
                    socket.emit('chatterbox comment', $('.form_comment_input').val(), user.name, evt.target.result);
                };

                reader.readAsDataURL(file);
                $('.chatterbox_comment_error').html("");
                comment_textarea.css('border', '1px solid #ccc');
            }
        }

        $('#chatterbox_comment_file_upload_1').val('');
});

What I am trying to do is on submit of this textarea, check if there are either only blank input and check to see if the file uploaded is valid (png jpg bmp or svg), if it is not, then display the error message. If it is valid, then send it to the node server. This function is somewhat working. It validates the completely blank input, but when trying to send an image it doesnt send it and it doesnt validate incorrect file uploads such as .pdf for example. I believe my if/else statements are somehow incorrectly written. Any suggestions? cheers

Aucun commentaire:

Enregistrer un commentaire