This is my validation code for a field title:
@NotNull(message = "Not null")
@NotBlank(message = "Not blank")
@Size(min = 10, max = 300, message = "min 10, max 300 characters")
private String title;
Other validations like the presented @NotNull or @Size are working fine. Only the @NotBlank is passed without error message when I input " abc xyz 123 " (with leading/last space).
I want it to give an error when there are spaces at the beginning/end of the string.
How can I validate to avoid leading/trailing whitespace?
@NotBlankannotation is used to check for null and empty strings (text with only white space characters).From the documentation:
For your use case, you might need to use the
@Patternvalidator. From the documentation of@Pattern:A pattern like
along with all your other annotations might fit what you're looking for. This pattern matches any text which does not begin with a white space and does not end with a white space.
Here's a Link to detailed explanation for this regex if you're new to regex
Note: the documentation texts are for
javax.validation.constraintsbut they're also valid forjakartaequivalent ones.Edit Original code modified to include this solution: