Use jQuery 'additional-methods.js' to validate 'Image Upload' Filesize

Support MB Frontend Submission Use jQuery 'additional-methods.js' to validate 'Image Upload' FilesizeResolved

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #40210
    CodogCodog
    Participant

    Hi there,
    I am trying to provide some feedback or error message to the end user if they upload an image using the "Image Upload" custom field, and their filesize exceeds the "max_file_size" set within it.

    The "max_file_size" works very effectively at REJECTING image uploads that exceed the limit, but provides no feedback or error to the end user. I have tried adding the "max_file_size" to the custom field validation methods but this also does not provide any feedback or error message?

    I have tried using jQuery additional-methods.js (Which I have implemented before for other kinds of custom validation) to achieve this using:

    $.validator.addMethod('filesize', function (value, element, param) {
        return this.optional(element) || (element.files[0].size <= param * 1000000)
    });

    Then referencing this within the custom field validation like this:

    'validation' => [
                'rules'    => [
                    $prefix . 'image_upload_test' => [
                        'extension' => 'jpeg, jpg, png',
    		    'filesize' => 1, // Not greater than 1mb
    		    'max_file_size' => '1mb',
                    ],
                ],
                'messages' => [
                    $prefix . 'image_upload_test' => [
                        'extension' => 'Must be a jpg or png file',
    		    'filesize' => 'Not greater than 1mb!',
    		    'max_file_size' => 'Not greater than 1mb!',
                    ],
                ],
            ],

    But this also does not seems to work?

    Q) Is this even possible? Is there an error in my methodology (above) or can you suggest another method to achieve this?

    I look forward to your response 🙂

    L

    #40217
    PeterPeter
    Moderator

    Hello,

    The validation in your code won't work because the rule filesize or max_file_size is not supported. Please read more on the documentation
    https://docs.metabox.io/validation/#advanced-validation
    https://jqueryvalidation.org/documentation/#link-list-of-built-in-validation-methods

    If you can create your own JS code to check the file size, you can implement a notice box like JS function alert() and prevent clicking the submit button.

    #40221
    CodogCodog
    Participant

    Ok, understood and thanks for getting back to me 🙂

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.