Skip to content
This repository has been archived by the owner on Mar 12, 2020. It is now read-only.

File Size validation #73

Closed
rudzikdawid opened this issue Feb 19, 2015 · 12 comments
Closed

File Size validation #73

rudzikdawid opened this issue Feb 19, 2015 · 12 comments
Labels

Comments

@rudzikdawid
Copy link

rudzikdawid commented Feb 19, 2015

JS:

Validator.VALIDATORS.filesize = function ($el) {
    var fileSizeMax = $el.data('filesize');
    return $el[0].files[0].size<=fileSizeMax
}

HTML:

<div class="form-group form-group-file">
    <input type="file" id="file" name="file" class="form-control" data-filesize="3000" data-filesize-error="Max 3000B" accept="image/*" />
    <div class="help-block with-errors"></div>
</div>

it is working but only with one input[type=file], when i have 2 input[type=file] even with error i can click submit and go to next page.
So I added to JS something like that:

jQuery('form[data-toggle="validator"] button[type="submit"]').on('click', function(event) {
  if ($('.form-group').hasClass('has-error')) {
    event.preventDefault();
  };
});

But it isn't best solution.
Any ideas how fix it?

@1000hz
Copy link
Owner

1000hz commented Feb 19, 2015

Make sure the file inputs are in separate .form-groups.

Also, you should probably guard against .files[0] being undefined.

if ($el[0].files[0] && $el[0].files[0].size > fileSizeMax) {}

I threw this into a JSBin and it seems to be working.
http://jsbin.com/xibisixita/1/edit?html,js,output

@rudzikdawid
Copy link
Author

Thank You
Now everything works perfectly :D

@abhiagrawal87
Copy link

abhiagrawal87 commented Aug 17, 2016

Hi, I am not able to validate my single file field. I have followed your code in JSBin however the validation happens only once when I click the field to select file. It shows file is required "Please select a file." and "Max 5MB".
Once a file is selected and do not matches the defined requirement of size and MIME type, there is no error.

HTML

<div class="form-group form-group-file">
    <label for="resume" class="control-label">Attach resume</label>
    <input type="file" class="form-control" id="resume" name="resume" required data-filesize="5242880" data-filesize-error="Max 5MB" accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/rtf">
    <p class="help-block">Microsoft Word or PDF file is allowed (5MB)</p>
    <div class="help-block with-errors"></div>
</div>

Validator.js

Validator.VALIDATORS = {
    'native': function ($el) {
      var el = $el[0]
      if (el.checkValidity) {
        return !el.checkValidity() && !el.validity.valid && (el.validationMessage || "error!")
      }
    },
    'match': function ($el) {
      var target = $el.data('match')
      return $el.val() !== $(target).val() && Validator.DEFAULTS.errors.match
    },
    'minlength': function ($el) {
      var minlength = $el.data('minlength')
      return $el.val().length < minlength && Validator.DEFAULTS.errors.minlength
    },
    'filesize': function ($el) {
      var fileSizeMax = $el.data('filesize');
      if ($el[0].files[0] && $el[0].files[0].size>fileSizeMax) {
        return false;
      } else {
        return true;
      }
    }
  }

@1000hz
Copy link
Owner

1000hz commented Aug 17, 2016

@abhiagrawal87 that example is from an old version of the validator. here's an updated example
http://jsbin.com/wijomelulo/1/edit?html,js,output

@abhiagrawal87
Copy link

Thanks for your prompt response. Your example is working for a standalone system however when I try to get the same result from a ajax driven form fields then it is not working.

@abhiagrawal87
Copy link

Hi, can you help me out with file size validation on Ajax form? I tried several options.. created separate file to test the functionality with Ajax but somehow validation after file selection is not working. Validations on all other fields are working seamlessly. Infact when I remove the file, then validation for "File is required" appears.

@1000hz
Copy link
Owner

1000hz commented Aug 17, 2016

I'm not sure what you are trying to do with ajax.

@abhiagrawal87
Copy link

@1000hz I can show you a working link. Can I have your email id?

What I am trying to achieve is:

  • I have a application which fetches all job openings from database using Ajax
  • Clicking on any such opening will show form to provide details and upload resume
  • I have all validations running on every input field including basic validation of required on file type field

Issue: I have defined a max file size to be 5mb and would like to validate before form is submitted. This validation is not happening. Might be it has to do something with Ajax.

Thanks

@1000hz
Copy link
Owner

1000hz commented Aug 17, 2016

you need to initialize the validator via JS with $('#myForm').validator({custom: fileSizeValidator}) once your form is shown. data-toggle="validator" only initializes the validator for forms already on the page when it first loads.

@abhiagrawal87
Copy link

@1000hz lots of tweaking and it finally worked for me. Thanks a lot 👍

@abhilashrajrs
Copy link

abhilashrajrs commented Dec 26, 2016

i want the file input only the image formats. how to do it

@pasindujayanath
Copy link

pasindujayanath commented Jun 17, 2018

@abhilashrajrs
follow this link Popular MIME types for more extensions/types.

myImageInput: {
    validators: {
        file: {
                extension: 'jpg,jpeg,png',
                type: 'image/jpg,image/jpeg,image/png',
                message: 'Please choose a valid image.'
        }
    }
}

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

5 participants