-4

I want to validate that 3 character ISO Country code coming in the request is valid or not using Java.

2 Digit Country code can be valid using this

But I want to validate for 3 character ISO code.

Java Version: 11

armandino
  • 17,625
  • 17
  • 69
  • 81
Jayesh Dhandha
  • 1,983
  • 28
  • 50
  • https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Locale.html#getISO3Language() apply this to the two-letters solution. – Federico klez Culloca Jul 16 '20 at 14:39
  • Does this answer your question? [Cleaner way to check if a string is ISO country of ISO language in Java](https://stackoverflow.com/questions/15921332/cleaner-way-to-check-if-a-string-is-iso-country-of-iso-language-in-java) – jhamon Jul 16 '20 at 14:39
  • the linked answer use Set of Strings. There is no limitation on the number of characters in each string – jhamon Jul 16 '20 at 14:40
  • what version of java you are using? – Amit Vyas Jul 16 '20 at 14:40
  • As i already mentioned, above given suggestions are good when we have incoming country code with 2 character. I am getting ISO code in 3 character. – Jayesh Dhandha Jul 16 '20 at 14:40
  • @AmitVyas I am using Java 11 – Jayesh Dhandha Jul 16 '20 at 14:41
  • @jhamon I have verified that, It's only working for 2 character country code. I have verified it by adding `IN` and `IND`. For `IN` it's giving true, for `IND` it's giving false – Jayesh Dhandha Jul 16 '20 at 14:45
  • you need to use java.util.Locale.getISO3Country. This opensource has Locale utilities – Amit Vyas Jul 16 '20 at 14:46
  • @AmitVyas It's a non static method and we can't call it directly. I have tried creating Locale object and passed like `Locale locale = new Locale("", "IND");` this is also working for 2 characters only. :( – Jayesh Dhandha Jul 16 '20 at 14:49
  • 2
    loop on `getAvailableLocales()` and call `getISO3Country` – jhamon Jul 16 '20 at 14:57
  • This is something which i should appreciate as an answer! Thanks man @jhamon – Jayesh Dhandha Jul 17 '20 at 05:15

1 Answers1

2

Sample code to get country name based on 3 Letter code. Tweak and you can make your own validation method.

  public static void main(String[] args) {
    Map<String, String> countriesMap = buildISOCodeAndCountryMap();
    String countryName = countriesMap.get("IND");
    System.out.println(countryName);

  }

  public static Map<String, String> buildISOCodeAndCountryMap() {
    Map<String, String> isoCodeAndCountryMap= new HashMap<String, String>();

    String[] isoCountries = Locale.getISOCountries();
    for (String country : isoCountries) {
      Locale locale = new Locale("", country);
      String iso = locale.getISO3Country();
      String code = locale.getCountry();
      String name = locale.getDisplayCountry();

      if (!"".equals(iso) && !"".equals(code)
          && !"".equals(name)) {
        isoCodeAndCountryMap.put(iso, name);
      }

    }
    return isoCodeAndCountryMap;
  }
Amit Vyas
  • 790
  • 3
  • 10