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

Change error messages #37

Open 10120128 opened 2 years ago

10120128 commented 2 years ago

Hi, I'm still clueless to change error message when using text-io, do I need to call withParseErrorMessagesProvider for every input reader that have been made?

Thanks.

siordache commented 2 years ago

Yes, because this method is intended to customize the error message of a specific input reader. There is currently no API method to set a global custom ErrorMessageProvider.

Here is an example of changing the error messages of an age input reader:

int age = textIO.newIntInputReader()
        .withDefaultValue(0)
        .withValueChecker((val, itemName) -> {
            if(val < 0) return List.of("How is this possible? Do you come from the future?");
            else if(val > 120) return List.of("Oh, come on! Nobody is that old.");
            else return null;
        })
        .withParseErrorMessagesProvider((sVal, itemName) -> List.of(
                "What do you mean by " + sVal + "?. Your age must be an integer number.",
                "Next time pay more attention."))
        .read("What's your age? (0 for exit)");

What is your use case?

10120128 commented 2 years ago

I just want to have custom error message and custom validation, and that code is exactly what I needed.

But days after tweaking it I get into more better solution, this code set the withMinLength to zero to be able to use custom validation and will loop and clean the console when there is an error:

String name;
textIO.getTextTerminal().setBookmark("name");
while (true) {
    name= textIO.newStringInputReader().withMinLength(0).read("Enter your name: ");
    if (name.length() < 3) {
        textIO.getTextTerminal().println("Name is not valid!");
        textIO.newStringInputReader().withMinLength(0).read("Press enter to continue.");
        textIO.getTextTerminal().resetToBookmark("name");
        continue;
    }
    break;
}

Thanks for the response :)