Skip to content

Commit

Permalink
feat: better handling of input validation for number
Browse files Browse the repository at this point in the history
  • Loading branch information
Nicola Di Falco committed Aug 7, 2023
1 parent 329067f commit c98d203
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -126,10 +126,14 @@ protected boolean read(BindingReader bindingReader, KeyMap<String> keyMap, Numbe
checkInput(input, context);
break;
case OPERATION_EXIT:
if (StringUtils.hasText(context.getInput())) {
var num = parseNumber(context.getInput());

if (num != null) {
context.setResultValue(parseNumber(context.getInput()));
}
else if (context.getDefaultValue() != null) {
} else if (StringUtils.hasText(context.getInput())) {
printInvalidInput(context.getInput(), context);
break;
} else if (context.getDefaultValue() != null) {
context.setResultValue(context.getDefaultValue());
} else if (required) {
context.setMessage("This field is mandatory", TextComponentContext.MessageLevel.ERROR);
Expand Down Expand Up @@ -161,14 +165,18 @@ private void checkInput(String input, NumberInputContext context) {
}
Number num = parseNumber(input);
if (num == null) {
String msg = String.format("Sorry, your input is invalid: '%s', try again", input);
context.setMessage(msg, MessageLevel.ERROR);
printInvalidInput(input, context);
}
else {
context.setMessage(null);
}
}

private void printInvalidInput(String input, NumberInputContext context) {
String msg = String.format("Sorry, your input is invalid: '%s', try again", input);
context.setMessage(msg, MessageLevel.ERROR);
}

public interface NumberInputContext extends TextComponentContext<Number, NumberInputContext> {

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -238,12 +238,19 @@ public void testResultUserInputInvalidInput() throws InterruptedException, IOExc

latch1.await(2, TimeUnit.SECONDS);

NumberInputContext run1Context = result1.get();
assertThat(consoleOut()).contains("input is invalid");
assertThat(run1Context).isNull();

NumberInputContext run1Context = result1.get();
// backspace 2 : cr + input
testBuffer.backspace(2).append("2").cr();
write(testBuffer.getBytes());

latch1.await(2, TimeUnit.SECONDS);

run1Context = result1.get();
assertThat(run1Context).isNotNull();
assertThat(run1Context.getResultValue()).isNull();
assertThat(run1Context.getResultValue()).isEqualTo(2);
}

@Test
Expand Down

0 comments on commit c98d203

Please sign in to comment.