HTTPS SSH

Validator.NET

Features

  • Fluent
  • Property validation
  • Collection validation
  • Conditional validation
  • No dependencies

Creating validator

var validator = new Validator<Foo>()
    .IsNotNullOrEmpty(x => x.Name);

or dedicated class

public class FooValidator : Validator<Foo>
{
    this.IsNotNullOrEmpty(x => x.Name);
}

Validating properties

Properties can be validated through lambda expressions

validator.Required(x => x.Name, "Name is required");

or via string key

validator.Required("Name", "Name is required");

List of bundled validations:

Comparable

  • IsGreaterThan
  • IsGreaterThanOrEqualTo
  • IsLessThan
  • IsLessThanOrEqualTo
  • IsEqualTo

String

  • IsNotNullOrEmpty
  • IsNull
  • MinLength
  • MaxLength
  • IsEmail
  • IsUri
  • IsDate
  • IsInteger
  • IsNumeric
  • Regex
  • RegexOrNull

Object

  • Required

Validating collections

public class Foo
{
    public Bar[] Bars { get; set; }
}

public class Bar
{
    public string Id { get; set; }
    public string Name { get; set; }
}
var barValidator = new Validator<Bar>()
    .Required(x => x.Id, "Id is required")
    .IsNumeric(x => x.Id, "Id must be numeric")
    .Required(x => x.Name, "Name is required");

var validator = new Validator<Foo>()
    .ValidCollection(x => x.Bars, barValidator, "Invalid collection");

var model = new Foo
{
    Bars = new[]
    {
        new Bar {Id = "1", Name = "test"},
        new Bar {Id = "asdf"},
        new Bar(),
    }
};

var summay = validator.Validate(model);
var isValid = summary.IsValid;
var res = summary.Results;

Conditional validation

public class Foo
{
    public bool HasStuff { get; set; }
    public string Stuff { get; set; }

    public bool HasOtherStuff { get; set; }
    public string OtherStuff { get; set; }
}
var validator = new Validator<Foo>()
    .When(x => x.HasStuff, v => v
        .Required(x => x.Stuff, "Stuff required")
        .When(x => x.HasOtherStuff, v2 => v2
            .Required(x => x.OtherStuff, "Other stuff is also required")
        )
    );