简体   繁体   中英

JQuery File input validation and hiding div

I have a couple of inputs

<div class="row">
    <div class="col-md-6 col-sm-offset-3 file-input">
        <div class="input-group">
            <input type="text" class="form-control" id="fileOneContainer" readonly>
        <span class="input-group-btn">
            <span class="btn btn-primary btn-file">
                Browse&hellip; <input type="file" id="fileOne" name="fileOne" class="fileGroup">
            </span>
        </span>
        </div>
    </div>
    <div class="col-md-6 col-sm-offset-3 file-input">
        <div class="input-group">
            <input type="text" class="form-control" id="fileTwoContainer" readonly>
            <span class="input-group-btn">
                <span class="btn btn-primary btn-file">
                    Browse&hellip; <input type="file" id="fileTwo" name="fileTwo" class="fileGroup">
                </span>
            </span>
        </div>
    </div>
</div>

Now I have to do my own custom validation for this within Javascript. Concentrating only on the first input for now, the rules are:

  • Cant be empty
  • Cant be larger than 2MB
  • Must be one of a certain file type

To handle all this, I came up with the following

var fileOne = $("#fileOne").val();

if(fileOne.length == 0) {
    $(this).addClass('error');
    errors.push("- Please upload a document");
} else if($("#fileOne")[0].files[0].size > 2097152) {
    errors.push("- Please upload a file smaller than 2MB");
} else if(  $("#fileOne")[0].files[0].type != 'image/bmp' &&
    $("#fileOne")[0].files[0].type != 'image/jpeg' &&
    $("#fileOne")[0].files[0].type != 'image/pjpeg' &&
    $("#fileOne")[0].files[0].type != 'image/png' &&
    $("#fileOne")[0].files[0].type != 'image/tiff' &&
    $("#fileOne")[0].files[0].type != 'application/pdf') {
    errors.push("- Please upload one of the valid document types");
}

This seems to work, although I imagine it could be improved.

Anyways, I need to now work on the second input. Initially, this input should be hidden, and only displayed when an add more button is clicked. Now I do not really want to hide it via css because this can be altered using developers tools.

The rules for the second input are pretty much the same as above, but this input is not required. This input should only have a value if the first input has a value. So you shouldnt be able to upload a file to the second input unless you have already uploaded one to the first.

What would be the best way to handle this second input to achieve the affect I am after?

Any advice appreciated.

Thanks

UPDATE So I now have this

    var fileInputs = document.querySelectorAll('.fileGroup');

    for (var i = 0; i < fileInputs.length; i++) {
        fileInputs[i].addEventListener('change', function(event){
            error = validateFile(event);
            errors.push(error);
        });
    };

function validateFile(event) {
    var input = event.target;
    var fileLength = input.files[0].length;
    var fileSize = input.files[0].size;
    var fileType = input.files[0].type;

    if(fileLength == 0) {
        $(this).addClass('error');
        return("- Please upload a document");
    } else if(fileSize > 2097152) {
        return("- Please upload a file smaller than 2MB");
    } else if(  fileType != 'image/bmp' &&
                fileType != 'image/jpeg' &&
                fileType != 'image/pjpeg' &&
                fileType != 'image/png' &&
                fileType != 'image/tiff' &&
                fileType != 'application/pdf') {
        return("- Please upload one of the valid document types");
    }
}

The problem is that I need the errors to display once the form has been submitted, not when the fileinput changes. Is there any way to do this without the change event?

Thanks

Try using accept attribute set to ".bmp,.jpeg,.jpg,.pjpeg,.png,.tiff,.pdf" , adding disabled to second input , setting disabled to false at change event handler of first input

 var errors = []; $(document).on("change", "#fileOne, #fileTwo:not(:disabled)", function() { console.log(this.files); if (this.files[0].size > 2097152) { errors.push("- Please upload a file smaller than 2MB"); }; if (this.files.length) { $("#fileTwo").prop("disabled", false) } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="row"> <div class="col-md-6 col-sm-offset-3 file-input"> <div class="input-group"> <input type="text" class="form-control" id="fileOneContainer" readonly> <span class="input-group-btn"> <span class="btn btn-primary btn-file"> Browse&hellip; <input type="file" id="fileOne" name="fileOne" class="fileGroup" accept=".bmp,.jpeg,.jpg,.pjpeg,.png,.tiff,.pdf"> </span> </span> </div> </div> <div class="col-md-6 col-sm-offset-3 file-input"> <div class="input-group"> <input type="text" class="form-control" id="fileTwoContainer" readonly> <span class="input-group-btn"> <span class="btn btn-primary btn-file"> Browse&hellip; <input type="file" id="fileTwo" name="fileTwo" class="fileGroup" accept=".bmp,.jpeg,.jpg,.pjpeg,.png,.tiff,.pdf" disabled="true"> </span> </span> </div> </div> </div> 

I recommend looping through your inputs and binding an on change event listener to validate the file. That way you don't have to repeat logic and you can grab the context via the event.

function validateFile(event) {
    var input = event.target;
    var fileSize = input.files[0].size;
    // rest of validation logic here.

}

var fileInputs = document.querySelectorAll('.fileGroup')

for (var i = 0; i < fileInputs.length; i++) {
    fileInputs[i].addEventListener('change', function(event){
        validateFile(event);
    });
};

The above starter code should put you in the right direction.

EDIT: If you'd like to do it on submit you can write some code like this:

document.forms[index].onsubmit = function() {
    validateFile();
}

The index is the index of the form on the page. If there is only one form it most likely is 0.

Here is a fiddle: http://jsfiddle.net/dgautsch/cep7cggr/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM