From cdd48f4fd45633bf9e04a474c3c0d696c365e592 Mon Sep 17 00:00:00 2001 From: Yusuke Wada Date: Sun, 28 Jul 2024 16:39:40 +0900 Subject: [PATCH] fix(validator): support `application/json` with a charset (#3199) --- src/validator/validator.test.ts | 12 ++++++++++++ src/validator/validator.ts | 4 ++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/validator/validator.test.ts b/src/validator/validator.test.ts index de4ac8834..64788fdc9 100644 --- a/src/validator/validator.test.ts +++ b/src/validator/validator.test.ts @@ -136,6 +136,18 @@ describe('JSON', () => { expect(res.status).toBe(200) }) + it('Should validate if Content-Type is a application/json with a charset', async () => { + const res = await app.request('http://localhost/post', { + method: 'POST', + headers: { + 'Content-Type': 'application/json; charset=utf8', + }, + body: JSON.stringify({ foo: 'bar' }), + }) + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ foo: 'bar' }) + }) + it('Should validate if Content-Type is a subtype like application/merge-patch+json', async () => { const res = await app.request('http://localhost/post', { method: 'POST', diff --git a/src/validator/validator.ts b/src/validator/validator.ts index 076fccb4d..b9c346a35 100644 --- a/src/validator/validator.ts +++ b/src/validator/validator.ts @@ -23,8 +23,8 @@ export type ValidationFunction< // eslint-disable-next-line @typescript-eslint/no-explicit-any type ExcludeResponseType = T extends Response & TypedResponse ? never : T -const jsonRegex = /^application\/([a-z-\.]+\+)?json$/ -const multipartRegex = /^multipart\/form-data(; boundary=[A-Za-z0-9'"()+_,\-./:=?]+)?$/ +const jsonRegex = /^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/ +const multipartRegex = /^multipart\/form-data(; boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/ const urlencodedRegex = /^application\/x-www-form-urlencoded$/ export const validator = <