I'm using Java Swing for a Connection GUI. I need to prevent entering whitespaces to the JTextField elements, especially to password field. I had used isEmpty() or isBlank() to know whether whitespaces are entered. But it didn't worked. If I enter whitespace it doesn't return true value,as isBlank() should return true if there is whitespace only.
String errorMessage = "No Errors"; //Intializing as No errors
private boolean checkValueAndSetErrorMessage(Map<String, String> map) {
boolean truth = false;
for (Map.Entry<String, String> mapElement : map.entrySet()) {
if (mapElement.getKey().isEmpty()|| mapElement.getKey().isBlank()) {
errorMessage = String.format("%1$s should not be blank.", mapElement.getValue()); //Changing errorMessage to empty
truth = false;
break;
} else {
truth = true;
}
}
return truth;
}
CodePudding user response:
Try :
mapElement.getKey().contains(" ")
CodePudding user response:
You can use regular expression
to test if the key contains any whitespace character.
Pattern.matches("\\s ", mapElement.getKey())
For more explanation in the regular expression that I provided,
\s
mean that it will try to match one or more whitespaces characters