0

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?

Question3r
  • 2,166
  • 19
  • 100
  • 200
  • You'll need to change your `int ProductId` to a nullable int like `int? ProductId` as explained [here](https://stackoverflow.com/questions/6662976/required-attribute-for-an-integer-value) – MindSwipe Jun 05 '20 at 07:02

1 Answers1

1

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; }
bit
  • 4,407
  • 1
  • 28
  • 50
  • thanks for your reply. So the correct fix for this is `public class OrderPosition { [Required] [Range(1, int.MaxValue)] public int ProductId { get; set; } [Required] [Range(1, int.MaxValue)] public int Amount { get; set; } }` ? because with a range starting at 0 it just takes the default value for integers? – Question3r Jun 05 '20 at 07:12
  • `[Required]` seems to be redundant, because the `Range` attribute seems to handle it. But what if you would want to validate an optional field only if set? Currently the `Range` attribute would mark that field as required – Question3r Jun 05 '20 at 07:16
  • Right you can remove Required, And you can keep the Amount's range from 0 unless 1 is the minimum Amount you expect – bit Jun 05 '20 at 07:16