1

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?

hc_dev
  • 8,389
  • 1
  • 26
  • 38
NqanVo
  • 21
  • 2
  • Please add the pom file and imports for NotNull and NotBlank to the question. Think is likely related to javax.validation vs jakarta.validation – John Williams Jun 17 '23 at 05:27
  • Is the input-string originating from a JSON-request? Are you using Jackson object-mapper to map the request? If so, I would suggest trimming before validation, see comments on [similar question](https://stackoverflow.com/questions/41447744/size-annotation-not-trimming-whitespace). – hc_dev Jun 19 '23 at 18:22

1 Answers1

1

@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;
  • Excellent answer explaining `@NotBlank` constraint and suggesting the adequate alternative `@Pattern` including a __testable regex-example__. – hc_dev Jun 19 '23 at 18:08