Created
October 24, 2025 10:24
-
-
Save akaia-shadowfox/be2573a8ff0fffedc750abbe543b7f0a to your computer and use it in GitHub Desktop.
Zod schemas for bcp47 tag validation. Supports both tags and subtags.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { isValid as isValidLanguageCode } from "@aleksejdix/ally-bcp47" | |
| import { isError } from "remeda" | |
| import { array, preprocess, string } from "zod" | |
| /** | |
| * All inline localization strings must be written in English. | |
| * Do not change this type, as it enforces the rule. | |
| */ | |
| type SourceLocaleId = "en" | |
| export const SOURCE_LOCALE_ID: SourceLocaleId = "en" | |
| export type LocaleIdArraySchemaParams = { | |
| defaultValue: string[] | |
| } | |
| export const localeIdArray = ( | |
| { defaultValue }: LocaleIdArraySchemaParams | undefined = { defaultValue: ["en"] }, | |
| ) => | |
| array(string(), "Must be an array of language code strings") | |
| .default(defaultValue) | |
| .refine( | |
| (values: string[]) => values.every(isValidLanguageCode), | |
| "Each locale id must be a valid BCP-47 language code", | |
| ) | |
| .refine( | |
| (values: string[]) => values.includes(SOURCE_LOCALE_ID), | |
| "Must contain the source locale ID", | |
| ) | |
| export type LocaleIdJsonArraySchemaParams = { | |
| default: LocaleIdArraySchemaParams["defaultValue"] | |
| } | |
| export const localeIdJsonArray = (params: LocaleIdJsonArraySchemaParams) => | |
| preprocess( | |
| (value: string | undefined, ctx) => { | |
| if (typeof value === "string") { | |
| try { | |
| return JSON.parse(value) as object | |
| } catch (err) { | |
| ctx.issues.push({ | |
| code: "custom", | |
| message: isError(err) ? err.message : "Invalid JSON", | |
| input: value, | |
| }) | |
| return undefined | |
| } | |
| } else return undefined | |
| }, | |
| localeIdArray({ defaultValue: params.default }), | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment