Search code examples
c#.netvalidationdto

How I'm suppose to validate a DTO?


I'm trying to create a web API with .net in C#

Although in my research I've encountered that is a big no-no placing validation code or data annotations attributes in DTOs, every tutorial that I see has something among this lines

[HttpPost]
public IActionResult Post(SomeDto someDto)
{
     if (ModelState.IsValid){
         //DoStuff();
     }
}

If i'm not wrong, the ModelState.IsValid check if the argument fulfils the validations requirement of the SomeDto dto. In example:

public class SomeDto    
{
    [Range(0, 10, ErrorMessage = "Price cannot be more that 10")] //this
    public decimal Price { get; set; }
}

Hence my question, should I place data annotations or any validation logic inside DTOs or not? how would it be the "cleaner" solution to this?


Solution

  • If you need to implement more complex logic for validation it's better to use tools like FluentValidator. In this case, you can separate classes and define custom validation logic and use validation attributes for the action or something like this:

    var validationResult = new MyModelValidator().Validate(dto);
    

    Separating validation logic from the model definition file makes it possible for validating a dto for Create and Update in different ways. The validator will be like this:

    public class MyModelValidator: AbstractValidator<SomeDto>
        {
            public MyModelValidator()
            {
                RuleFor(x => x.Id)
                    .Empty()
                    .WithMessage(DefaultMessages.InvalidInput);
    
                RuleFor(x => x.Name)
                    .NotEmpty()
                    .WithMessage(DefaultMessages.InvalidName)
                    .Length(2, 80)
                    .WithMessage(DefaultMessages.InvalidName);
            }
        }