Note
This library is at the alpha stage.
Fluffy is a small, dependency-free validation library for .NET. Define predicates for a reference type, associate error messages with them, and collect every failed rule in one call.
Inherit from Fluf<T> and add rules in a public parameterless constructor. A rule
passes when its predicate returns true.
using Fluffy;
public class User
{
public int Id { get; set; }
public string Name { get; set; } = "";
}
public class UserValidator : Fluf<User>
{
public UserValidator()
{
_ = Define(user => user.Id > 0, "Id must be greater than zero.")
.Define(user => !string.IsNullOrWhiteSpace(user.Name), "Name is required.");
}
}Define returns the same validator, so rules can be chained. If you omit the
message, a failed rule uses Generic error message for Type User (with the name
of your validated type in place of User).
Register the assembly containing your validators once at application startup:
using Fluffy;
Fluf.RegisterValidators(typeof(UserValidator).Assembly);Then call the Resolve() extension method on an object:
using Fluffy;
var user = new User
{
Id = 0,
Name = ""
};
var (validation, errors) = user.Resolve();
if (!validation)
{
foreach (string error in errors)
{
Console.WriteLine(error);
}
}Output:
Id must be greater than zero.
Name is required.
Resolve returns a (bool validation, IEnumerable<string> errors) tuple. It
evaluates all rules, returning failed-rule messages in definition order. When all
rules pass, validation is true and errors is empty. A validator with no rules
also succeeds.
RegisterValidators accepts multiple assemblies and discovers concrete,
closed types derived from Fluf<T>. Re-registering an assembly does nothing;
each Resolve() extension call creates a fresh validator instance.
Only one validator can be registered per validated type. Duplicate validators or
a validator without a public parameterless constructor cause registration to
throw InvalidOperationException.
The extension method looks up the exact generic type T inferred at the call
site, not the object's runtime type. If no validator is registered for that type,
it returns true with no errors. It throws ArgumentNullException for a null
object.
Create a validator yourself and pass the object to its Resolve method. This
does not require assembly registration:
var validator = new UserValidator();
var user = new User
{
Id = 1,
Name = "Alex"
};
var (validation, errors) = validator.Resolve(user);Both validation paths execute your predicates directly. Exceptions from a predicate propagate to the caller rather than becoming validation errors.
Use ApplyRule when you only need a boolean result, without a validator,
registration, or error messages:
using Fluffy;
bool hasName = user.ApplyRule(value => !string.IsNullOrWhiteSpace(value.Name));