javaif-statementunicodejtextfieldhebrew

Force the user to add only Hebrew letters


How can I make a JTextfield accept only Hebrew letters with if statement? I can do a long if statement with all the Hebrew letters but it will not look good.
I found out that the Unicode of Hebrew first letter is \u05D0 and last one is \u05EA.
How can I say that if the gettext is in between these 2 letters so show (meaning to check if the text entered is only a Hebrew letter), the user will add only one letter in each textfield.
Thank you in advance


Solution

  • Since you are using JTextField and this class inherits getText() method which returns a String. So, this is how I will probably do it.

    String name = jTextField.getText();
    char[] charArray = name.toCharArray();
    for (char c : charArray) {
        if (!(c <= 0x05ea && c >= 0x05d0)) {
            break;
            //valid
        }
    }
    

    This can become more efficient, if you keep the counter of elements added/removed, you only will have to check the latest entered character (in case of removal you probably won't need that but that scenario will need more coding, so I hope you will figure that out once you solves this issue).

    Update:

    This is what I have tried:

            String name      = "אבגa";
            char[] charArray = name.toCharArray();
            for (char c : charArray) {
                if (c <= 0x05ea && c >= 0x05d0) {
                    System.out.println("Valid hebrew");
                }
            }
    

    And this prints Valid hebrew three times.