@NotBlank
annotation is used to check for null and empty strings (text with only white space characters).
From the documentation:
The annotated element must not be null and must contain at least one non-whitespace character. Accepts CharSequence.
For your use case, you might need to use the @Pattern
validator. From the documentation of @Pattern
:
The annotated CharSequence must match the specified regular expression. The regular expression follows the Java regular expression conventions see Pattern.
Accepts CharSequence. null elements are considered valid.
A pattern like
(?=^[^\s].*)(?=.*[^\s]$).*
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.constraints
but they're also valid for jakarta
equivalent ones.
Edit
Original code modified to include this solution:
@NotNull(message = "Not null")
@Pattern(regexp = "(?=^[^\\s].*)(?=.*[^\\s]$).*", message = "No leading or trailing white spaces")
@Size(min = 10, max = 300, message = "min 10, max 300 characters")
private String title;