Skip to content

Commit

Permalink
feat: add validateLanguageTag (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
kazupon authored Sep 20, 2023
1 parent bcabb0d commit 3795c4d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
17 changes: 17 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
16 changes: 15 additions & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand Down Expand Up @@ -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)
})
})

0 comments on commit 3795c4d

Please sign in to comment.