jakartaee / jakartaee/validation
Empty `Optional<@NotBlank String>` fails validation
- Dominant language
- Java
- Stars
- 163
- Forks
- 67
- Avg merge
- 3d 15h
- Merged PRs (30d)
- 2
Description
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!
Contributor guide
Research direction
Start with the Jakarta Bean Validation 3.0 sections on built-in value extractors and the @NotBlank constraint, then review the linked Quarkus issue for context. A useful outcome would be an agreed specification decision or documented rationale for how @NotBlank should behave with empty Optional values.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java
- Domain
- api, backend
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 20/100