# General Translation Platform: isValidLocale URL: https://generaltranslation.com/zh/docs/platform/core/reference/utility-functions/locales/is-valid-locale.mdx --- title: isValidLocale description: 无需 GT 实例即可检查某个值是否为有效的区域设置代码。isValidLocale 的 API 参考。 --- [`isValidLocale`](/docs/platform/core/reference/gt-class-methods/locales/is-valid-locale) 是 General Translation Core 库提供的一个独立实用函数,用于验证某个字符串是否为有效的 BCP-47 区域设置代码。它无需 GT 实例即可执行格式验证。 ## 概览 [#overview] 直接从 `generaltranslation` 导入 `isValidLocale`,并传入区域设置代码进行调用。它既不需要 API Key,也不需要 [GT](/docs/platform/core/reference/gt-class/constructor) 实例。若要使用基于实例的等效方式,请改用 [`GT`](/docs/platform/core/reference/gt-class/constructor) 实例上的 [`isValidLocale`](/docs/platform/core/reference/gt-class-methods/locales/is-valid-locale) 方法。 ```typescript import { isValidLocale } from 'generaltranslation'; console.log(isValidLocale('en-US')); // true console.log(isValidLocale('invalid')); // false ``` 签名: ```typescript isValidLocale(locale: string, customMapping?: CustomMapping): boolean ``` ## 工作方式 [#how-it-works] * **格式验证。** 验证 BCP-47 区域设置代码的格式。这仅是格式验证——不会发出任何网络请求。 * **自定义映射。** 支持自定义区域设置映射,因此在 [`customMapping`](/docs/platform/core/reference/types/custom-mapping) 中定义的别名也会被视为有效。 * **无状态。** 适合用于工具库和用户输入验证。 ## 参数 [#parameters] | 参数 | 描述 | 类型 | 可选 | 默认值 | | ---------------------------------- | -------------- | --------------------------------------------------------------------- | -- | --- | | [`locale`](#locale) | 要验证的值。 | `string` | 否 | — | | [`customMapping`](#custom-mapping) | 验证时需要考虑的自定义映射。 | [`CustomMapping`](/docs/platform/core/reference/types/custom-mapping) | 是 | — | ### `locale` [#locale] **类型** `string` · **必填** 要验证的值,应为 BCP-47 区域设置代码。 ### `customMapping` [#custom-mapping] **类型** [`CustomMapping`](/docs/platform/core/reference/types/custom-mapping) · **可选** 一个可选的自定义映射,其别名会被视为有效。 ## 返回值 [#returns] **类型** `boolean` 如果区域设置代码有效,则返回 `true`,否则返回 `false`。 ## 示例 [#examples] ```typescript import { isValidLocale } from 'generaltranslation'; // 有效的区域设置代码 console.log(isValidLocale('en-US')); // true console.log(isValidLocale('zh-CN')); // true console.log(isValidLocale('es')); // true // 无效的区域设置代码 console.log(isValidLocale('invalid')); // false console.log(isValidLocale('en_US')); // false(下划线而非连字符) console.log(isValidLocale('')); // false ``` ## 说明 [#notes] * 验证 BCP-47 区域设置代码的格式。 * 支持自定义区域设置映射。 * 对用户输入验证必不可少。 * 不发起网络请求——仅验证格式。 * 这是一个无状态函数,适合用于工具库。