Home > Software design >  FluentValidation for List parameter
FluentValidation for List parameter

Time:04-01

We have an existing API endpoint with a signature like the following (simplified):

[HttpPost("api/v1/data")]
public DataSubmission SubmitData([FromBody] List<DataItem> items) {
  ...
}

public class DataItemValidator : AbstractValidator<DataItem> {
  // RuleFor(...)
}

We have defined a validator for the DataItem but we cannot figure out how to register the validation on the individual list items. For regular input models where the list is exposed as a property, it is convenient to use RuleForEach(x => x.ListPropertyName).SetValidator(...) but we fail to find a setup where we can validate the items when the model to validate is a list in itself.

We have attempted to define a derived model for this list and create a validator for it like this:

public class DataItemList : List<DataItem> {
}

public class DataItemListValidator : AbstractValidator<DataItemList> {
  public DataItemListValidator(){
    // How to set validator for items list??
  }
}

Are we going about this the wrong way or are there other ways to handle this scenario?

EDIT: I am aware of FluentValidation not being suitable for validating parameters (https://github.com/FluentValidation/FluentValidation/issues/337) but I am not sure if this applies as well since it seems to be somewhat of a grey area

CodePudding user response:

(Found an answer shortly after posting question)

We can achieve the validation using the derived model and a specific RuleForEach syntax:

public class DataListItemValidator : AbstractValidator<DataItemList> {
  public DataListItemValidator() {
    RuleForEach(x => x).SetValidator(new DataItemValidator());
  }
}

The key here is the (x => x) that allows for iterating the element of itself.

  • Related