Search code examples
javagwtdetectalphanumericchars

Test if two first chars typed in are alphanumeric - no regex


I have following code that needs something smart to deal with typed in chars and detection:

private final MultiWordSuggestOracle mySuggestions = new MultiWordSuggestOracle();
private final Set<String> mySuggestionsData = new HashSet<String>();

@UiHandler("suggestBox")
public void onKeyPress(KeyDownEvent event) {
    if (Character.isLetterOrDigit(event.getCharCode())) {
        char[] text = suggestBox.getText().trim().toCharArray();
        if (text.length != 1) return;

        for (char ch : text) {
            if (!Character.isLetterOrDigit(ch)) {
                return;
            }
        }
        //load data from server into mySuggestionsData
    }     
}

The question has 3 parts:

  1. How do you test pressed key against alphanumeric chars. Keep in mind this is GWT so I would rather not use regex ( but if there is no other option ...).

  2. What is the best way to detect the length of text typed into the SuggestBox?

  3. Is KeyDownEven the best choise? And why is it triggered twice when any key is pressed?


Solution

  • Instead of handling events, you should make your own SuggestOracle (possible wrapping a MultiSuggestOracle used as an internal cache) and check the query's length and "pattern" there to decide whether to call the server or not (and then give an empty list of suggestions as the response, or maybe a single suggestion being the exact query).

    As a side note, I don't understand why you don't want to use a regex; either using the java.lang.String methods taking a regex as a String, or the com.google.gwt.regexp.shared.RegExp class.