Jeremy Cook
Jeremy Cook

Reputation: 22073

Form wide unobtrusive jQuery validation

I've added my own "maxfilesize" jquery.validate method, and am using the unobtrusive validation script from Microsoft. The following is working, but I'm wondering if there a better way to do this with unobtrusive jquery validation?

Here's the signature of my validator add-on. It sums the size of every file input element in the form it is within, and errors if the total upload size is greater than maxMB.

$.validator.addMethod('maxfilesize', function (value, element, maxMB) { ... });

I place this just before the opening <form> element. It's just a dummy input element that I'm using to trigger form validation.

<form>
  <input maxfilesize="4" style="visibility: hidden" aria-hidden="true" />

  <input type="file" name="Files" />
  <input type="file" name="Files" />
  <input type="file" name="Files" />

  <button type="submit">Upload Files</button>
</form>

I wish I could place the maxfilesize attribute directly on the form element, but unobtrusive jquery validation doesn't pay any attention to it. Any suggestions?

Upvotes: 0

Views: 137

Answers (1)

Sudipta Kumar Maiti
Sudipta Kumar Maiti

Reputation: 1709

Why are you not checking HTML5 file size? A post is available here

<input type="file" name="Files" id="myFile1"/>
<input type="file" name="Files" id="myFile2"/>
<input type="file" name="Files" id="myFile3"/>

var myFile1Size = document.getElementById('myFile1').files[0].size;
// check file size
var myFile2Size = document.getElementById('myFile2').files[0].size;
// check file size
var myFile3Size = document.getElementById('myFile3').files[0].size;
// check file size

Upvotes: 0

Related Questions