11

How to check whether the array is empty or not using class-validator.
Given below is my structure. I want to check if cartId is empty or not.

{
   "cartId": []
}
2
  • You can use @IsNotEmpty(). Commented Apr 17, 2020 at 6:24
  • 4
    @IsNotEmpty() doesn't catch an empty array, because [] IS a non-empty value. As the selected answer show,s you must use @ArrayNotEmpty() Commented Jul 22, 2022 at 13:57

2 Answers 2

32

What you want is @ArrayNotEmpty(). You can find all built-in validators here: https://github.com/typestack/class-validator#validation-decorators

If you don't find - you can write your own validator: https://github.com/typestack/class-validator#custom-validation-classes

Sign up to request clarification or add additional context in comments.

1 Comment

Really close in name to @IsNotEmpty(). Could see that catching people
1

To check if array is empty, you can use @ArrayNotEmpty(), like this:

@ArrayNotEmpty({ each: true })
cartId: [];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.