UNPKG

@gravityforms/utils

Version:
39 lines (34 loc) 1.36 kB
/** * @function getValidLocale * @description Returns a valid locale string. * * @since 4.0.8 * * @param {string} locale The locale string to validate. * @param {string} fallback The fallback locale string. * * @return {string} The valid locale string. */ const getValidLocale = ( locale = '', fallback = 'en-US' ) => { try { if ( ! locale ) { // Throw to enter the catch block for consistent handling. throw new Error( 'Locale not provided' ); } // The Intl.Locale constructor validates the structural correctness of the locale string. const localeObj = new Intl.Locale( locale ); // We then use Intl.DateTimeFormat to check for runtime support. const resolvedLocale = new Intl.DateTimeFormat( locale ).resolvedOptions().locale; // If the resolved language differs from the requested language, it indicates the // environment has fallen back to a default locale because the requested one is unsupported. if ( new Intl.Locale( resolvedLocale ).language !== localeObj.language ) { throw new Error( `Unsupported locale: ${ locale }` ); } return resolvedLocale; } catch ( e ) { // All errors (invalid structure, unsupported, or empty) are handled here. console.warn( `The locale ${ locale } is invalid or unsupported, falling back to ${ fallback }.` ); return fallback; } }; export default getValidLocale;