Skip to content

Repository files navigation

Readme

Give a Star 🌟

If you liked the project or if FluentOptionValidation helped you, please give a star.

Purpose

FluentValidationOption(OptionValidationSharp) provides option validation with Fluent Validation.

How To Use(?)

Install

dotnet add package OptionValidationSharp

Example appsettings.json file

"AppSettings": {
    "ApplicationName": "MyApp",
    "MaxUsers": 500,
    "Url": "https://github.com"
  }

Example Option Class

public class AppSettings
{
    public string? ApplicationName { get; set; }
    
    public int MaxUsers { get; set; }
    
    public string? Url { get; set; }
}

Example Option Validation Class

public class AppSettingsValidator : AbstractValidator<AppSettings>
{
    public AppSettingsValidator()
    {
        RuleFor(r => r.ApplicationName).NotEmpty();
        RuleFor(r => r.MaxUsers).InclusiveBetween(1,100);
        RuleFor(r => r.Url).NotEmpty();
        RuleFor(r => r.Url)
            .Must(url => Uri.TryCreate(url, UriKind.Absolute, out _))
            .When(r => !string.IsNullOrWhiteSpace(r.Url));
    }
}

Use in Program.cs

builder.Services.AddValidatorsFromAssembly(typeof(Program).Assembly);

builder.Services.AddOptions<AppSettings>()
    .Bind(builder.Configuration.GetSection("AppSettings"))
    .ValidateOptionSharp() // <- 🔨 Validation Option with Fluent Validation
    .ValidateOnStart();

Result:

fail: Microsoft.Extensions.Hosting.Internal.Host[11]
Hosting failed to start
Microsoft.Extensions.Options.OptionsValidationException: Options validation failed for type 'AppSettings'. 'Max Users' must be between 1 and 100. You entered 500.

About

This repo, provides option pattern validation with Fluent Validation

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

Used by

Contributors

Languages