Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't prevent file upload on failed validation using jQuery Form plugin

Here's my form:

<form id="frmUpload" action="../scripts/upload.php" method="post" enctype="multipart/form-data">
    <div id="sermonInfo">
        File: <input type="file" id="uploadedFile" name="uploadedFile" class="error"><br>
        <br>
        Title: <input type="text" id="title" name="sermonTitle" size="35" maxlength="100">
    </div>
</form>
<div id="uploadInfo">
    <div class="progress">
        <div class="statusBar" style="width: 0%;"></div>
        <div class="percent">0%</div>
    </div>

    <div id="status"></div>
    <br>
    <div id="required">Only mp3 files are allowed!</div>
</div>

And here's the JS I'm using:

<script>
    $(function() {
        /*
         * Upload
         */
        // Reset validation and progress elements
        var formValid = true,
            percentVal = '0%';
        $('#uploadedFile, #title').removeClass('error');
        $('#status, #required').empty().removeClass();
        $('.statusBar').width(percentVal)
        $('.percent').html(percentVal);

        $('form').ajaxForm({
            beforeSend: function(e) {

                if (!ValidateUploadForm()) {
                    formValid = false;
                    console.log('validateuploadform returned false');
                } else {
                    console.log('validateuploadform returned true');
                    formValid = true;
                }

                console.log('in beforeSend. formValid: ' + formValid);

                if (!formValid) {
                    return false;
                }

            },
            uploadProgress: function(event, position, total, percentComplete) {
                console.log('in uploadProgress function. formValid: ' + formValid);
                if (formValid) {
                    var percentVal = percentComplete + '%';
                    $('.statusBar').width(percentVal)
                    $('.percent').html(percentVal);    
                }
            },
            complete: function(xhr) {
                console.log('in complete function. formValid: ' + formValid);
                if (formValid) {
                    console.log('xhr.responseText: ' + xhr.responseText);
                    console.log('formValid: ' + formValid);

                    if (xhr.responseText === 'success') {
                        $('.statusBar').width('100%');
                        $('.percent').html('100%');
                        $('#status').html('Successfully uploaded the file.').addClass('successUpload');

                        // Clear the form
                        ClearForm();

                    } else if (xhr.responseText === 'fail') {
                        $('#status').html('There was a problem uploading the file. Try again.<br>If the problem persists, contact your system administrator.').addClass('errorUpload');
                    }
                }
            }
        }); // End Upload Status Bar
    });

    function ValidateUploadForm() {
        // Reset errors and clear message
        $('#uploadedFile, #title').removeClass('error');
        $('#required').empty();

        var result = true;
            title = $('#title').val(),
            fileName = $('#uploadedFile').val();
            extension = $('#uploadedFile').val().split('.').pop();

        if (fileName !== '' && extension !== 'mp3') {
            $('#uploadedFile').addClass('error');
            $('#required').html('Only mp3 files are allowed!');
            return false;
        } else if (fileName === '') {
            result = false;
        } else if (title === '') {
            $('#title').addClass('error');
            result = false;
        }

        console.log('returning ' + result + ' from the validateuploadform function');

        if (!result) { $('#required').html('All fields are required.'); }
            return result;
        }

        function ClearForm() {
            $('#uploadedFile, #title').val('').removeClass();
    }
</script>

As you can see, I'm using console output the keep an eye on what's going on.

My problem is, if a file is selected, the file still uploads, whether formValid (in beforeSend) is true or false.

I've tried adding preventDefault before return false;. I've also tried clearing the file input in the if (!formValid) {} block. As you can see, I've wrapped the uploadProgress and complete functions to check if formValid is false. If the console output in uploadProgress shows formValid to be false, the file still uploads.

What am I missing here? How can I prevent the file upload if the validation fails?

like image 364
marky Avatar asked May 05 '26 13:05

marky


2 Answers

I finally figured out the issue: I was comparing my script to some examples online and noticed that the examples' callback was named beforeSubmit, but I was using beforeSend.

Oddly, the validation code was still executing, but returning false didn't stop the upload.

like image 141
marky Avatar answered May 07 '26 06:05

marky


Basically, it looks like you might be missing the jquery.form.js extension. Without JavaScript console output, I can only guess that that ought to be the problem. Try the following (entire) page as a reference, where stopping the upload works:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Test Page</title>

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js" type="text/javascript">
</script>
<script src="http://malsup.github.com/jquery.form.js" type="text/javascript">
</script>
<style type="text/css">
 div.c1 {width: 0%;}
</style>
</head>
<body>
<form id="frmUpload" action="%3C?php%20basename(__FILE__,%20'.php');%20?%3E" method="post" enctype="multipart/form-data" name="frmUpload">
<div id="sermonInfo">File: <input type="file" id="uploadedFile" name="uploadedFile" class="error"><br>
<br>
Title: <input type="text" id="title" name="sermonTitle" size="35" maxlength="100"></div>
<input type="submit" value="Submit"></form>
<div id="uploadInfo">
<div class="progress">
<div class="statusBar c1"></div>
<div class="percent">0%</div>
</div>
<div id="status"></div>
<br>
<div id="required">Only mp3 files are allowed!</div>
</div>
<script type="text/javascript">
    $(function() {
        /*
         * Upload
         */
        // Reset validation and progress elements
        var formValid = true,
            percentVal = '0%';
        $('#uploadedFile, #title').removeClass('error');
        $('#status, #required').empty().removeClass();
        $('.statusBar').width(percentVal)
        $('.percent').html(percentVal);

        $('form').ajaxForm({
            beforeSend: function(e) {

                if (!ValidateUploadForm()) {
                    formValid = false;
                    console.log('validateuploadform returned false');
                } else {
                    console.log('validateuploadform returned true');
                    formValid = true;
                }

                console.log('in beforeSend. formValid: ' + formValid);

                if (!formValid) {
                    return false;
                }

            },
            uploadProgress: function(event, position, total, percentComplete) {
                console.log('in uploadProgress function. formValid: ' + formValid);
                if (formValid) {
                    var percentVal = percentComplete + '%';
                    $('.statusBar').width(percentVal)
                    $('.percent').html(percentVal);    
                }
            },
            complete: function(xhr) {
                console.log('in complete function. formValid: ' + formValid);
                if (formValid) {
                    console.log('xhr.responseText: ' + xhr.responseText);
                    console.log('formValid: ' + formValid);

                    if (xhr.responseText === 'success') {
                        $('.statusBar').width('100%');
                        $('.percent').html('100%');
                        $('#status').html('Successfully uploaded the file.').addClass('successUpload');

                        // Clear the form
                        ClearForm();

                    } else if (xhr.responseText === 'fail') {
                        $('#status').html('There was a problem uploading the file. Try again.<br>If the problem persists, contact your system administrator.').addClass('errorUpload');
                    }
                }
            }
        }); // End Upload Status Bar
    });

    function ValidateUploadForm() {
        // Reset errors and clear message
        $('#uploadedFile, #title').removeClass('error');
        $('#required').empty();

        var result = true;
            title = $('#title').val(),
            fileName = $('#uploadedFile').val();
            extension = $('#uploadedFile').val().split('.').pop();

        if (fileName !== '' && extension !== 'mp3') {
            $('#uploadedFile').addClass('error');
            $('#required').html('Only mp3 files are allowed!');
            return false;
        } else if (fileName === '') {
            result = false;
        } else if (title === '') {
            $('#title').addClass('error');
            result = false;
        }

        console.log('returning ' + result + ' from the validateuploadform function');

        if (!result) { $('#required').html('All fields are required.'); }
            return result;
        }

        function ClearForm() {
            $('#uploadedFile, #title').val('').removeClass();
    }
</script>
</body>
</html>

As a side note, you might want to use

extension = $('#uploadedFile').val().split('.').pop().toLowerCase();

to make sure that the form also accepts MP3, as this is seen relatively often too in the wild.

If this doesn't fix your problem, it would help if you could upload the full HTML of one page in question.

UPDATE

With respect to the uploaded files, you have a simple typo in line 91 of testUpload.php:

if ((fileName === '') || (extension !== 'mp3'))

should be

if ((fileName === '') || (extension !== 'mp3')) {
like image 43
likeitlikeit Avatar answered May 07 '26 05:05

likeitlikeit