-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
dimensions.ts
52 lines (43 loc) · 1.19 KB
/
dimensions.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { RuleParamSchema } from '../types';
const validateImage = (file: File, width: number, height: number): Promise<boolean> => {
const URL = window.URL || (window as any).webkitURL;
return new Promise(resolve => {
const image = new Image();
image.onerror = () => resolve(false);
image.onload = () => resolve(image.width === width && image.height === height);
image.src = URL.createObjectURL(file);
});
};
const validate = (files: File | File[], { width, height }: Record<string, any>) => {
const list = [];
files = Array.isArray(files) ? files : [files];
for (let i = 0; i < files.length; i++) {
// if file is not an image, reject.
if (!/\.(jpg|svg|jpeg|png|bmp|gif)$/i.test(files[i].name)) {
return Promise.resolve(false);
}
list.push(files[i]);
}
return Promise.all(list.map(file => validateImage(file, width, height))).then(values => {
return values.every(v => v);
});
};
const params: RuleParamSchema[] = [
{
name: 'width',
cast(value) {
return Number(value);
}
},
{
name: 'height',
cast(value) {
return Number(value);
}
}
];
export { validate, params };
export default {
validate,
params
};