Why @NotBlank not violated when leading/trailing space

406 views Asked by At

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?

1

There are 1 answers

1
Pranav Sricharan On

@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;