Skip to content

Commit c98d203

Browse files
author
Nicola Di Falco
committed
feat: better handling of input validation for number
1 parent 329067f commit c98d203

File tree

2 files changed

+22
-7
lines changed

2 files changed

+22
-7
lines changed

spring-shell-core/src/main/java/org/springframework/shell/component/NumberInput.java

+13-5
Original file line numberDiff line numberDiff line change
@@ -126,10 +126,14 @@ protected boolean read(BindingReader bindingReader, KeyMap<String> keyMap, Numbe
126126
checkInput(input, context);
127127
break;
128128
case OPERATION_EXIT:
129-
if (StringUtils.hasText(context.getInput())) {
129+
var num = parseNumber(context.getInput());
130+
131+
if (num != null) {
130132
context.setResultValue(parseNumber(context.getInput()));
131-
}
132-
else if (context.getDefaultValue() != null) {
133+
} else if (StringUtils.hasText(context.getInput())) {
134+
printInvalidInput(context.getInput(), context);
135+
break;
136+
} else if (context.getDefaultValue() != null) {
133137
context.setResultValue(context.getDefaultValue());
134138
} else if (required) {
135139
context.setMessage("This field is mandatory", TextComponentContext.MessageLevel.ERROR);
@@ -161,14 +165,18 @@ private void checkInput(String input, NumberInputContext context) {
161165
}
162166
Number num = parseNumber(input);
163167
if (num == null) {
164-
String msg = String.format("Sorry, your input is invalid: '%s', try again", input);
165-
context.setMessage(msg, MessageLevel.ERROR);
168+
printInvalidInput(input, context);
166169
}
167170
else {
168171
context.setMessage(null);
169172
}
170173
}
171174

175+
private void printInvalidInput(String input, NumberInputContext context) {
176+
String msg = String.format("Sorry, your input is invalid: '%s', try again", input);
177+
context.setMessage(msg, MessageLevel.ERROR);
178+
}
179+
172180
public interface NumberInputContext extends TextComponentContext<Number, NumberInputContext> {
173181

174182
/**

spring-shell-core/src/test/java/org/springframework/shell/component/NumberInputTests.java

+9-2
Original file line numberDiff line numberDiff line change
@@ -238,12 +238,19 @@ public void testResultUserInputInvalidInput() throws InterruptedException, IOExc
238238

239239
latch1.await(2, TimeUnit.SECONDS);
240240

241+
NumberInputContext run1Context = result1.get();
241242
assertThat(consoleOut()).contains("input is invalid");
243+
assertThat(run1Context).isNull();
242244

243-
NumberInputContext run1Context = result1.get();
245+
// backspace 2 : cr + input
246+
testBuffer.backspace(2).append("2").cr();
247+
write(testBuffer.getBytes());
244248

249+
latch1.await(2, TimeUnit.SECONDS);
250+
251+
run1Context = result1.get();
245252
assertThat(run1Context).isNotNull();
246-
assertThat(run1Context.getResultValue()).isNull();
253+
assertThat(run1Context.getResultValue()).isEqualTo(2);
247254
}
248255

249256
@Test

0 commit comments

Comments
 (0)