-
Notifications
You must be signed in to change notification settings - Fork 9
Add FluentValidation to validate the parsed options
Matthias Beerens edited this page Nov 5, 2019
·
1 revision
You need to add the following package to your project that will allow to use FluentValidation
with CommandLineParser
PM> Install-Package MatthiWare.CommandLineParser.Extensions.FluentValidations
using FluentValidation;
using MatthiWare.CommandLine.Extensions.FluentValidations;
static void Main(string[] args)
{
var parser = new CommandLineParser<ProgramOptions>();
// Plugin the FluentValidation library
parser.UseFluentValidations(configurator
=> configurator.AddValidator<ProgramOptions, ProgramOptionValidator>());
// Rest of the configuration..
}
// The options
public class ProgramOptions
{
[Required, Name("user", "username"), Description("Login user")]
public string Username { get; set; }
[Required, Name("pw", "password"), Description("Password for the user")]
public string Password { get; set; }
[Required, Name("p", "port"), Description("port for the server"), DefaultValue(3333)]
public int Port { get; set; }
}
// The FluentValidation implementation
public class ProgramOptionValidator : AbstractValidator<ProgramOptions>
{
public ProgramOptionValidator()
{
RuleFor(o => o.Password).MinimumLength(5);
RuleFor(o => o.Username).MinimumLength(5);
RuleFor(o => o.Port).InclusiveBetween(1000, 30000);
}
}