Skip to content

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

@ivamly

Description

@ivamly

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions