The ASP.NET Core Model State Validator fully abstracted to use in any .NET Core application.
This lib allows you to use the ASP.NET Core Model State Validator in any .NET Core project.
Don't use this for ASP.NET Core MVC and ASP.NET Core Webapi projects you probably don't need that for these projects that already has this validation type implemented with the IObjectModelValidator, this lib will probably have no conflict if you inject in the dependency container.
You can add this lib via nuget package manager.
Dotnet cli example:
dotnet add package ModelStateValidation
You can use this lib as a static class or with the IServiceProvider dependendency container.
Inject this lib in your IServiceCollection like that:
IServiceCollection services = new ServiceCollection();
services.AddModelStateValidation();
Equals to ASP.NET Core you can pass configurations for this with an action:
IServiceCollection services = new ServiceCollection();
services.AddModelStateValidation(options =>
{
options.MaxModelValidationErrors = 200;
});
For use this, just get the IModelStateValidator from the dependency provider like that:
var validator = provider.GetService<IModelStateValidator>();
// Pass the object to be valitaded and it will return true if is valid.
var isValid = validator.TryValidateModel(model);
Obs: any service injected in dependency container can get this service in your constructor.
Not every project has dependency injection, so this lib supports static usage:
var isvalid = ModelStateValidator.TryValidateModel(model);
You can decide if you'll pass a ModelStateDictionary a model name prefix or no.
See this example with a ModelStateDictionary and a empty prefix:
var modelState = new ModelStateDictionary(200);
var prefix = string.Empty;
var isValid = validator.TryValidateModel(model, modelState, prefix);
// Here all overloads:
isValid = validator.TryValidateModel(model);
isValid = validator.TryValidateModel(model, modelState);
isValid = validator.TryValidateModel(model, prefix);
isValid = validator.TryValidateModel(model, modelState, prefix);
This project uses the MIT License.