Fluent validation for parameters

You can use FluentValidation with this library to validate argument models.

Here's an example,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Program
{
    static int Main(string[] args)
    {
        AppRunner<ValidationApp> appRunner = new AppRunner<ValidationApp>();
        return appRunner.Run(args);
    }
}
public class ValidationApp
{
    public void ValidateModel(PersonModel person)
    {
        string content = JsonConvert.SerializeObject(person, Formatting.Indented);
        Console.WriteLine(content);
    }
}

[Validator(typeof(PersonValidator))]
public class PersonModel : IArgumentModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Email { get; set; }
}

public class PersonValidator : AbstractValidator<PersonModel>
{
    public PersonValidator()
    {
        RuleFor(x => x.Id).GreaterThan(0);
        RuleFor(x => x.Name).NotEmpty();
        RuleFor(x => x.Email).NotEmpty().EmailAddress();
    }
}

If the validation fails, app exits with return code 2 and prints validation error messages on screen.


Last update: February 22, 2020