validation icon indicating copy to clipboard operation
validation copied to clipboard

Empty `Optional<@NotBlank String>` fails validation

Open krnhotwings opened this issue 1 year ago • 1 comments

Hi folks, it was suggested that I should create an issue here to start a discussion about the behavior of @NotBlank. Relevant issue here:

https://github.com/quarkusio/quarkus/issues/41262

tldr is that an empty Optional<@NotBlank String> will fail validation, and the reason is because:

  1. The Optional value extractor returns null if empty: https://jakarta.ee/specifications/bean-validation/3.0/jakarta-bean-validation-spec-3.0.html#valueextractordefinition-builtinvalueextractors
  2. @NotBlank must have at least 1 non-whitespace character and must not be null, as noted in the javadoc for the annotation: https://jakarta.ee/specifications/bean-validation/3.0/jakarta-bean-validation-spec-3.0.html#builtinconstraints-notblank

Marko suggested implementing one of the following to get around the issue:

  • Create a custom optional value extractor
  • Create a custom "null or not blank" annotation + validator

While either option works, I suppose the main question is: Why does @NotBlank consider null to be invalid? The behavior seems inconsistent to me because @Email and @Pattern are also constraints against CharSequence, but these two consider null to be valid. If a developer wanted an element to be not-nullable, wouldn't it be more appropriate to use @NotNull in conjunction with whatever other constraints needed? (e.g. @NotNull @NotEmpty String)

There's probably some historical reason for this behavior, but I'm not sure if it's documented anywhere. Some insight regarding this issue would be very much appreciated, if this behavior can be changed in future specs or if the solution is to simply roll our own solutions.

Thanks!

krnhotwings avatar Jul 18 '24 16:07 krnhotwings

Hello, today I ran into the same issue. Currently, I work around this problem by creating a custom NotBlank annotation that accepts null values as valid.

Kind regards

fatihcatalkaya avatar Mar 23 '25 23:03 fatihcatalkaya