| 2 |
lars |
1 |
// Accept a value from a file input based on a required mimetype
|
|
|
2 |
$.validator.addMethod( "accept", function( value, element, param ) {
|
|
|
3 |
|
|
|
4 |
// Split mime on commas in case we have multiple types we can accept
|
|
|
5 |
var typeParam = typeof param === "string" ? param.replace( /\s/g, "" ) : "image/*",
|
|
|
6 |
optionalValue = this.optional( element ),
|
|
|
7 |
i, file, regex;
|
|
|
8 |
|
|
|
9 |
// Element is optional
|
|
|
10 |
if ( optionalValue ) {
|
|
|
11 |
return optionalValue;
|
|
|
12 |
}
|
|
|
13 |
|
|
|
14 |
if ( $( element ).attr( "type" ) === "file" ) {
|
|
|
15 |
|
|
|
16 |
// Escape string to be used in the regex
|
|
|
17 |
// see: https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
|
|
|
18 |
// Escape also "/*" as "/.*" as a wildcard
|
|
|
19 |
typeParam = typeParam
|
|
|
20 |
.replace( /[\-\[\]\/\{\}\(\)\+\?\.\\\^\$\|]/g, "\\$&" )
|
|
|
21 |
.replace( /,/g, "|" )
|
|
|
22 |
.replace( /\/\*/g, "/.*" );
|
|
|
23 |
|
|
|
24 |
// Check if the element has a FileList before checking each file
|
|
|
25 |
if ( element.files && element.files.length ) {
|
|
|
26 |
regex = new RegExp( ".?(" + typeParam + ")$", "i" );
|
|
|
27 |
for ( i = 0; i < element.files.length; i++ ) {
|
|
|
28 |
file = element.files[ i ];
|
|
|
29 |
|
|
|
30 |
// Grab the mimetype from the loaded file, verify it matches
|
|
|
31 |
if ( !file.type.match( regex ) ) {
|
|
|
32 |
return false;
|
|
|
33 |
}
|
|
|
34 |
}
|
|
|
35 |
}
|
|
|
36 |
}
|
|
|
37 |
|
|
|
38 |
// Either return true because we've validated each file, or because the
|
|
|
39 |
// browser does not support element.files and the FileList feature
|
|
|
40 |
return true;
|
|
|
41 |
}, $.validator.format( "Please enter a value with a valid mimetype." ) );
|