jakartaee / jakartaee/validation

[PROPOSAL] New annotation for nullable @NotBlank / @NotEmpty validation

Open
#316 0 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Java
Stars
163
Forks
67
Avg merge
3d 15h
Merged PRs (30d)
2

Description

I've noticed an inconsistency in the default behavior of the constraint API. With the exception of @Null, almost all constraints in the jakarta.validation.constraints package consider a null value as valid. This is a well-documented and generally useful behavior, as it allows developers to handle optional fields by combining constraints with @NotNull only when required.

However, the @NotEmpty and @NotBlank constraints are notable exceptions to this rule. They explicitly fail on null values.

This creates an inconvenience when validating optional fields. For example, if I have an optional string field that should be non-blank if it's present, there is no clear and declarative way to express this.

The cleanest workaround is creating a custom constraint, which adds boilerplate and complexity for a seemingly common use case.

I understand that changing the default behavior of @NotBlank and @NotEmpty would be a massive breaking change and is not feasible for backward compatibility reasons.

Therefore, I would like to propose the introduction of a new annotation, for example:

  • @NotBlankOrNull
  • @NotBlankIfPresent

This new annotation would validate that a string is not blank only if it is present (i.e., not null). A null value would be considered valid. This would bring the behavior in line with other constraints, providing a consistent and declarative way to validate optional, non-blank strings.

If this is better suited for incubation in a specific provider (like Hibernate Validator) first, please let me know, and I would be happy to open an issue there instead.

Thank you for your time and consideration.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the Jakarta Validation constraint API and the existing @NotBlank and @NotEmpty semantics described in the issue. Determine whether a new nullable non-blank constraint belongs in the specification or should incubate in a provider such as Hibernate Validator; agreement on the annotation and its behavior would define done.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
backend-api-design
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.