diff --git a/src/index.ts b/src/index.ts index 50ecb93..980dfdb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -24,3 +24,20 @@ export function parseAcceptLanguage(value: string): string[] { !(tag === '*' || tag === '') ) } + +/** + * validate the language tag whether is a well-formed {@link https://datatracker.ietf.org/doc/html/rfc4646#section-2.1 | BCP 47 language tag}. + * + * @param {string} lang a language tag + * + * @returns {boolean} Returns `true` if the language tag is valid, else `false`. + */ +export function validateLanguageTag(lang: string): boolean { + try { + // TODO: if we have a better way to validate the language tag, we should use it. + new Intl.Locale(lang) + return true + } catch { + return false + } +} diff --git a/test/index.test.ts b/test/index.test.ts index e2930d0..2ca08d6 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -1,5 +1,9 @@ import { describe, expect, test } from 'vitest' -import { isLocale, parseAcceptLanguage } from '../src/index.ts' +import { + isLocale, + parseAcceptLanguage, + validateLanguageTag, +} from '../src/index.ts' describe('isLocale', () => { test('Locale instance', () => { @@ -41,3 +45,13 @@ describe('parseAcceptLanguage', () => { expect(parseAcceptLanguage('')).toEqual([]) }) }) + +describe('validateLanguageTag', () => { + test('valid', () => { + expect(validateLanguageTag('en-US')).toBe(true) + }) + + test('invalid', () => { + expect(validateLanguageTag('j')).toBe(false) + }) +})