beryx / text-io

A library for creating interactive console applications in Java
http://text-io.beryx.org/
Apache License 2.0
342 stars 45 forks source link

Error Message Provider for EnumInputReader with Numbered Values #24

Closed Jprnp closed 4 years ago

Jprnp commented 4 years ago

It would be great if we had the possibility to replace the standard "Enter a value between 1 and X" error message in the EnumInputReader. I'm developing an application in Portuguese, so the default english message doesn't fit well.

By debugging i found that there isn't any checks for a Message Provider in the method getValueFromIndex of class InputReader:

private T getValueFromIndex(String sVal, TextTerminal<?> textTerminal) {
        try {
            int optIndex = Integer.parseInt(sVal);
            if (optIndex > 0 && optIndex <= this.possibleValues.size()) {
                return this.possibleValues.get(optIndex - 1);
            }
        } catch (NumberFormatException var4) {
        }

        textTerminal.executeWithPropertiesPrefix("error", (t) -> {
            textTerminal.print(this.getDefaultErrorMessage(sVal));
            textTerminal.println(" Enter a value between 1 and " + this.possibleValues.size() + ".");
        });
        textTerminal.println();
        return null;
}
siordache commented 4 years ago

@Jprnp I released the version 3.4.0, which provides the method withInvalidIndexErrorMessagesProvider. Usage example:

Month month = textIO.newEnumInputReader(Month.class)
        .withInvalidIndexErrorMessagesProvider((val, propName, minIdx, maxIdx) ->
                Arrays.asList(
                        "Sorry, but '" + val + "' is not a valid option.",
                        "Please enter an integer value between " + minIdx + " and " + maxIdx + "."
                ))
        .read("What month were you born in?");
Jprnp commented 4 years ago

Nice. It works!

Issue solved, thanks!