Question3r
Question3r

Reputation: 3802

how to create dto validation for nested objects

I started with an API endpoint to create a new order for one customer by its customer id

[HttpPost("{id:int}/orders")]
public async Task<ActionResult<object>> CreateCustomerOrderByIdAsync(CreateCustomerOrderByIdDto createCustomerOrderByIdDto)
{
    // ...
}

So the DTO itself should validate the whole request. The customer id is a required field, the order positions are optional, the order itself can be empty.

public class CreateCustomerOrderByIdDto
{
    [FromRoute]
    [Required]
    public int Id { get; set; }

    [FromBody]
    public OrderPosition[] OrderPositions { get; set; }
}

Each OrderPositions knows about the ProductId and the Amount. Both fields are required for this instance in the array.

public class OrderPosition
{
    [Required]
    public int ProductId { get; set; }

    [Required]
    [Range(1, int.MaxValue)]
    public int Amount { get; set; }
}

When I call the endpoint https://localhost:5001/customers/1/orders with the following json body

{
    "orderPositions": [{}]
}

I would expect a 400 because the array holds an object with no ProductId or Amount field. But instead of the error it takes the default value for integers which is 0. How can I validate each OrderPosition inside the OrderPositions array too?

Upvotes: 0

Views: 478

Answers (1)

bit
bit

Reputation: 4487

You need to use Range on the ProductId as well. If your ProductId starts from 1 then it would look like below:

[Required]
[Range(1, int.MaxValue)]
public int ProductId { get; set; }

Upvotes: 1

Related Questions