Skip to content

Commit

Permalink
fix: handle mimes with plus symbol closes #4230
Browse files Browse the repository at this point in the history
  • Loading branch information
logaretm committed May 7, 2023
1 parent 298577b commit f5b3482
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/nasty-apples-destroy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@vee-validate/rules': patch
---

handle mimes with plus signs
17 changes: 14 additions & 3 deletions packages/rules/src/mimes.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import { isEmpty } from './utils';

const ADDED_MIME_RE = /\+(.+)?/;

function buildRegExp(mime: string) {
let strPattern = mime;
if (ADDED_MIME_RE.test(mime)) {
strPattern = mime.replace(ADDED_MIME_RE, '(\\+$1)?');
}

return new RegExp(strPattern.replace('*', '.+'), 'i');
}

const mimesValidator = (files: unknown, mimes: string[]) => {
if (isEmpty(files)) {
return true;
Expand All @@ -9,12 +20,12 @@ const mimesValidator = (files: unknown, mimes: string[]) => {
mimes = [];
}

const regex = new RegExp(`${mimes.join('|').replace('*', '.+')}$`, 'i');
const patterns = mimes.map(buildRegExp);
if (Array.isArray(files)) {
return files.every(file => regex.test((file as File).type));
return files.every(file => patterns.some(p => p.test((file as File).type)));
}

return regex.test((files as File).type);
return patterns.some(p => p.test((files as File).type));
};

export default mimesValidator;
6 changes: 6 additions & 0 deletions packages/rules/tests/mimes.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import validate from '../src/mimes';
import helpers from './helpers';

test('validates mime types', () => {
const params = ['image/*', 'text/plain'];

Expand All @@ -16,3 +17,8 @@ test('validates mime types', () => {

expect(validate(helpers.file('file.pdf', 'application/pdf'), params)).toBe(false);
});

test('mimes with regex characters', () => {
expect(validate(helpers.file('file.svg', 'image/svg'), ['image/svg+xml'])).toBe(true);
expect(validate(helpers.file('file.svg', 'image/xml'), ['image/svg+xml'])).toBe(false);
});

0 comments on commit f5b3482

Please sign in to comment.