3

I've got some text fields in my Android application that need to be limited to letters only (and possibly some enumerated set of basic symbols, like "._-,!" and so forth). My first instinct is to use the Java isLetter function. But I don't know if that's localization-friendly - my application needs to be localized into Japanese, among other languages, and the Android documentation gives no hints as to how that might work (whether isLetter depends on the current language, or all installed languages, or just some whitelist of Unicode characters). I know I can't tell the Android keyboard to not allow emoji entry, so I've got be able to check the text string after it's entered and accept it if it's okay, and reject it with an error if emoji characters (or others are detected).

Is there a generally accepted way of doing this in Android?

malderi
  • 33
  • 2

1 Answers1

0

isLetter should do what you need. Here is an example:

public boolean isAlpha(String name) {
    char[] chars = name.toCharArray();

    for (char c : chars) {
        if(!Character.isLetter(c)) {
            return false;
        }
    }

    return true;
}

Also, Japanese characters are still chars, so they would still work. The way to do that has to do with encoding.

A String is just a sequence of characters (chars); a String in itself has no encoding at all. For what it's worth, replace characters in the above with carrier pigeons. Same thing. A carrier pigeon has no encoding. Neither does a char.

From Check if String contains only letters

and UTF-8 Encoding ; Only some Japanese characters are not getting converted

Community
  • 1
  • 1
Jase Pellerin
  • 397
  • 1
  • 2
  • 13
  • 1
    After doing some further testing, it looks like you're correct - isLetter does accept Japanese and other language characters. I wish the documentation was clearer on this point on exactly what it accepts, but it'll work for now. – malderi Dec 03 '14 at 20:10