Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a locale in java?

Tags:

java

locale

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?

like image 620
u123 Avatar asked Sep 10 '10 12:09

u123


1 Answers

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

like image 81
Arne Burmeister Avatar answered Sep 20 '22 11:09

Arne Burmeister