class-validator icon indicating copy to clipboard operation
class-validator copied to clipboard

feat: add `@IsStrictlyOptional()` decorator filtering only missing `undefined` values

Open ehenon opened this issue 4 months ago • 2 comments

Description

As mentioned/discussed in some issues and PRs, proposal to add a new decorator based on the same philosophy as @IsOptional(), but filtering only values that are actually missing (=== undefined). Equivalent to @ValidateIf((o, v) => v !== undefined), but more direct and explicit.

Checklist

  • [x] the pull request title describes what this PR does (not a vague title like Update index.md)
  • [x] the pull request targets the default branch of the repository (develop)
  • [x] the code follows the established code style of the repository
    • npm run prettier:check passes
    • npm run lint:check passes
  • [x] tests are added for the changes I made (if any source code was modified)
  • [x] documentation added or updated
  • [x] I have run the project locally and verified that there are no errors

References

references #491, #2615, #686

ehenon avatar Sep 18 '25 14:09 ehenon

I think it makes more sense to use this decorator in the way I suggested. My view of “optional” in a DTO is: if the property is not present in the request body, validation should be skipped; if it is present (even if null or undefined), validation should run.

Using propertyName in object achieves this behavior:

Property absent → skip validation

Property present → run validation

This way, the decorator better reflects the semantic meaning of “optional” and avoids the confusion of skipping validation only for undefined, which doesn’t fully cover real-world use cases.

AntonioJRM1998 avatar Oct 02 '25 19:10 AntonioJRM1998

yes, I need this too.

yaquawa avatar Oct 06 '25 06:10 yaquawa