3
\$\begingroup\$

My form comprises of a mandatory file input.

  • The form is validated according to the jQuery validate plugin.

  • The file input has attribute required so that the validator recognises it as a mandatory field.

enter image description here


Problem statement:

Each time the user selects a file, the value of the file input is immediately reset to "". This is done to allow the same file to be uploaded again (see here) and cannot be changed by me.

Since the file input is mandatory, its value must be non-empty to be marked as valid. However, the file input is validated after the value has been reset to "", so the input is always marked as invalid, even if the user has selected a file.

See demo here


Solution:

Step 1: Each time the user selects a file, store the value of the selected file(s) in a data- attribute of the file input:

$('input[type=file]').change(function() {
  
  $(this).data('files', $(this).val());
 
});

Step 2: Change the way the validator accesses the value of the file input. To do this I modify the elementValue function (line 718 of the plugin source) to use $element.data('files') instead of using $element.val() for file inputs:

$.extend( $.validator.prototype, {
    
    elementValue: function( element ) {
            ...
            ...

            if ( isContentEditable ) {
                val = $element.text();
            } else if (type === "file") {
                val = $element.data("files") === undefined ? "" : $element.data("files");
            } else {
                val = $element.val();
            }

            ...
            ...
  });

***See demo here***


Concerns:

I am wary of overwriting 'elementValue' in this way as it is an internal function of the plugin.

It doesn't seem too dangerous since the return value of the modified 'elementValue' function is the same as that of the original, so any modifications I have made are restricted to that single function and won't spill over to the rest of the plugin. But I'm not sure of this and would be grateful for any guidance as I am new to jQuery/JS and don't have any collaborators to think this through with.

Another drawback I can think of is that I will always have to check the solution's compatibility with future releases of the plugin.

\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.