I would like to organize the verification of model fields so that all validation of all fields of a model class takes place in one validator class, which in turn returns an array of objects with a description of errors found, if any.

I found three validation methods:

  1. Using the class - ValidationAttribute;

This method seemed to me inappropriate because it involves the use of a single attribute to validate a single field. I want to create a class that will validate all the required fields at once, while causing validation error information for each field.

  1. Using the interface - IValidatableObject

This method satisfies my need to simultaneously check all fields and provide all validation errors found, but I don’t like the idea that the implementation of validation should be directly in the model class.

  1. Using the interface - IModelValidator

Using the IModelValidator interface, you can create a custom attribute for validating model data that can be applied to the model property:

public class LanguageValidator : Attribute, IModelValidator { public IEnumerable<ModelValidationResult> Validate(ModelValidationContext context) { throw new NotImplementedException(); } } 

As far as I understand, this method suggests the possibility of creating a validator in the form of an attribute with the possibility of validating all the fields of a class and the possibility of returning the corresponding array of errors found. In all the examples I found, this method was applied only to the class fields.

Tell me :

  • Is it possible using the IModelValidator interface to create validation attributes that would be applied not to the model properties but to the model class itself?

  • If there is any way to create a validation attribute that would allow within itself to validate all the fields of a class at once, while returning an array of all errors found for each of the fields?

  • Do you want DTO to validate this or business logic? - tym32167
  • @ tym32167 - Model - and. I wanted to use one attribute per class to validate all the fields I needed, with the possibility of getting an array of errors + so that the ability to interact with the "ModelState.IsValid" property in the controller action methods would be preserved. - Evgeniy Miroshnichenko

0