I read a file in an application that specifies a language code:
public void setResources(String locale) { // validate locale // ULocale lo = new ULocale(locale); // System.out.println(lo.getDisplayCountry()); }
that must be in the format: <ISO 639 language code>_<ISO 3166 region code>
eg. en_UK, en_US etc. Is it possible to validate that the locale string is valid before continuing?
I do not know ULocale, but if you mean java.util.Locale
, the following code may do:
public void setResources(String locale) { // validate locale Locale lo = parseLocale(locale); if (isValid(lo)) { System.out.println(lo.getDisplayCountry()); } else { System.out.println("invalid: " + locale); } } private Locale parseLocale(String locale) { String[] parts = locale.split("_"); switch (parts.length) { case 3: return new Locale(parts[0], parts[1], parts[2]); case 2: return new Locale(parts[0], parts[1]); case 1: return new Locale(parts[0]); default: throw new IllegalArgumentException("Invalid locale: " + locale); } } private boolean isValid(Locale locale) { try { return locale.getISO3Language() != null && locale.getISO3Country() != null; } catch (MissingResourceException e) { return false; } }
EDIT: added validation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With