0

I'm trying to add a new method to check file type, then check size based on type. In this case I want to allow jpg files up to 10MB and gif, png and pdf of 4MB. The upload field is not required, but I still need to validate file type and max file size of type. Currently, the error shows regardless of the file size.

I only want the error to show when the file selected is larger than allowed for its type. Not sure what I am missing. Any help or feedback is greatly appreciated.

Here is my HTML code

<form id="aspnetForm">
<p class="denote-required">
    <span class="required-symbol">*</span> = Required Field
</p>
<fieldset>
    <legend><h3>Details of item lost</h3></legend>
    <div class="form-group has-float-label required">
        <input
            type="text"
            id="date"
            name="date"
            class="form-control"
            data-toggle="datetimepicker"
            data-target="#date"
            placeholder=" "
            required />
        <label for="date">Date item lost</label>
    </div>
    <div class="form-group has-float-label required">
        <input
            type="text"
            id="route"
            name="route"
            class="form-control"
            placeholder=" "
            required />
        <label for="route">Route</label>
    </div>
    <div class="form-group has-float-label required">
        <textarea
            id="itemDescription"
            name="itemDescription"
            class="form-control"
            aria-describedby="descriptionHelpBlock"
            placeholder=" "
            required></textarea>
        <label for="itemDescription">Description</label>
        <div id="descriptionHelpBlock" class="form-text text-muted">
            <small>Please be as descriptive as possible, such as color, size, brand name etc.</small>
        </div>
    </div>
    <div class="input-group">
        <div class="custom-file">
            <input
            type="file"
            id="fileUpload"
            name="fileUpload"
            class="custom-file-input"
            aria-describedby="fileUploadHelpBlock" />
            <label for="fileUpload" class="custom-file-label">Add photo</label>
        </div>
        <div id="fileUploadHelpBlock" class="form-text text-muted">
            <small>File type can be .jpg, .jpeg, .gif or .png. The maximum file size limit for .jpeg/.jpg files is 10mb. The maximum file size limit for .gif and .png is 4mb</small>
        </div>
    </div>
</fieldset>
<fieldset>
    <legend><h3>Your contact infomation</h3></legend>
    <div class="form-group has-float-label required">
        <input
            type="text"
            id="name"
            name="name"
            class="form-control"
            placeholder=" "
            required />
        <label for="name">Name</label>
    </div>
    <div class="form-group has-float-label required">
        <input
            type="email"
            id="email"
            name="email"
            class="form-control"
            placeholder=" "
            required />
        <label for="email">Email</label>
    </div>
    <div class="form-group has-float-label">
        <input
            type="text"
            id="phone"
            name="phone"
            class="form-control"
            placeholder=" " />
        <label for="phone">Phone</label>
    </div>
</fieldset>
<fieldset>
    <legend><h3>Return by mail</h3></legend>
    <div class="custom-control custom-checkbox">
        <input
            type="checkbox"
            id="mailItem"
            name="mailItem"
            class="custom-control-input" />
        <label for="mailItem" class="custom-control-label">If found, return item by mail</label>
    </div>
    <div id="mailingAddress">
        <p>Please provide your mailng address to have the item mailed to you, if we are able to find it.</p>
        <div class="form-group has-float-label required">
            <input
                type="text"
                id="address"
                name="address"
                class="form-control"
                placeholder=" " />
            <label for="address">Address</label>
        </div>
        <div class="form-group has-float-label">
            <input
                type="text"
                id="address2"
                name="address2"
                class="form-control"
                placeholder=" " />
            <label for="address2">Address 2</label>
        </div>
        <div class="form-group has-float-label required">
            <input
                type="text"
                id="city"
                name="city"
                class="form-control"
                placeholder=" " />
            <label for="city">City</label>
        </div>
        <div class="form-group has-float-label required">
            <input
                type="text"
                id="state"
                name="state"
                class="form-control"
                placeholder=" " />
            <label for="state">State</label>
        </div>
        <div class="form-group has-float-label required">
            <input
                type="text"
                id="zipCode"
                name="zipCode"
                class="form-control"
                placeholder=" " />
            <label for="zipCode">Zip code</label>
        </div>
    </div>
</fieldset>
<hr />
<div class="ml-auto text-center">
    <button type="submit" class="btn btn-primary">Submit</button>
</div>

Here is the js code

const validateForm = (function ($, window, document, undefined) {

        $.validator.addMethod('maxFileSize', function (value, element) {
            return this.optional(element) || checkFileSize(value, element);
        });

        var checkFileSize = function (fileNames, files) {
            const ext = $(files);
            if ($.inArray(ext, ['gif', 'jpeg', 'jpg', 'png', 'pdf']) >= 0) {
                // Check file size
                const fileSize = $(element)[0].files[0].size;

                if (ext === 'gif' || ext === 'png' || ext === 'pdf') {
                    if (fileSize > 4000000) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    if (ext === 'jpeg' || ext === 'jpg') {
                        if (fileSize > 10000000) {
                            return false;
                        } else {
                            return true;
                        }
                    }
                }
            }
        }

        const init = function () {

            // Set rules and messages
            $('#aspnetForm').validate({
                debug: true,
                errorElement: 'div',
                errorClass: 'is-invalid',
                validClass: 'is-valid',
                rules: {
                    fileUpload: {
                        required: false,
                        accept: 'image/gif,image/jpg,image/jpeg,image/png,application/pdf,',
                        maxFileSize: true,
                    },
                },
                messages: {
                    date: 'Please select a date.',
                    route: 'Please enter a route.',
                    description: 'Please enter a description.',
                    fileUpload: {
                        accept: 'The file selected is not a valid type.',
                        maxFileSize: 'The file selected is too large.',
                    },
                    name: 'Please provide your name.',
                    email: 'Please enter a valid email',
                    address: 'Please enter your street address.',
                    city: 'Please enter a city.',
                    state: 'Please enter a state.',
                    zipCode: 'Please enter a zip code.',
                },

                errorPlacement: function (error, element) {
                    // Add the `help-block` class to the error element
                    error.addClass('help-block');

                    element
                        .parents('.form-group, .input-group, .custom-control')
                        .addClass('has-feedback');

                    if (
                        element.prop('type') === 'checkbox' ||
                        element.prop('type') === 'radio'
                    ) {
                        error.appendTo(element.parents('.custom-control'));
                    } else if (
                        element.prop('type') === 'file'
                    ) {
                        error.appendTo(element.parents('.input-group'));
                    } else {
                        error.appendTo(element.parents('.form-group, .input-group'));
                    }
                },
                highlight: function (element, errorClass, validClass) {
                    $(element)
                        .parents('.form-group, .input-group, .custom-control')
                        .addClass(errorClass)
                        .removeClass(validClass);

                    // Sets error icon.
                    $(element)
                        .next('.alert-red')
                        .show();
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element)
                        .parents('.form-group, .input-group, .custom-control')
                        .addClass(validClass)
                        .removeClass(errorClass);
                    $(element)
                        .next('.alert-red')
                        .remove();
                },
            });

            // Show address form when checked
            $('#mailingAddress').hide();
            $('#mailItem').click(function () {
                if ($(this).is(':checked')) {
                    $('#mailingAddress').fadeIn(300);
                    $('#mailingAddress [aria-required="true"]').attr('required', 'required');
                } else if ($(this).is(':not(:checked)')) {
                    $('#mailingAddress').fadeOut(300);
                    $('#mailingAddress [aria-required="true"]').removeAttr('required', 'required');
                }
            });
        };

        return {
            init: init,
            checkFileSize: checkFileSize,
        };
    })(jQuery, window, document);

    $(document).ready(function () {
        validateForm.init();
    });
Rich
  • 23
  • 5

1 Answers1

0

I was not properly setting 'ext' in the checkFileSize variable. After fixing that I also had to update fileSize variable within it.

Here's the updated js

var checkFileSize = function (files) {
const ext = files.files[0].name.split('.').pop().toLowerCase();
if ($.inArray(ext, ['gif', 'jpeg', 'jpg', 'png', 'pdf']) >= 0) {
    // Check file size
    const fileSize = files.files[0].size;

    if (ext === 'gif' || ext === 'png' || ext === 'pdf') {
        if (fileSize > 4000000) {
            return false;
        } else {
            return true;
        }
    } else {
        if (ext === 'jpeg' || ext === 'jpg') {
            if (fileSize > 10000000) {
                return false;
            } else {
                return true;
            }
        }
    }
}
return false;
}
Rich
  • 23
  • 5