Apply custom validators
Requires: abstractions module, main module (constraints).
Validation feature allows to associate a custom user-made validator with a settings type. Validation occurs during binding and results in binding errors for incorrect settings.
[ValidateBy(typeof(MySettingsValidator))]
class MySettings
{
int CacheCapacity { get; }
}class MySettingsValidator: ISettingsValidator<MySettings>
{
// Returns validation errors. Empty enumerable == success.
public IEnumerable<string> Validate(MySettings settings)
{
if (settings.CacheCapacity <= 0)
yield return "Cache capacity must be positive.";
}
}Constraints
There are also built-in validation constraints you can use to create a custom validator. Just inherit your validator class from ConstraintsValidator and override a method returning constraints to be checked:
[ValidateBy(typeof(TestConfigValidator))]
class TestConfig
{
public int Number;
public string String;
}class TestConfigValidator : ConstraintsValidator<TestConfig>
{
protected override IEnumerable<Constraint<TestConfig>> GetConstraints()
{
yield return new NotNullOrWhitespaceConstraint<TestConfig>(settings => settings.String);
yield return new RangeConstraint<TestConfig, int>(settings => settings.Number, 2, 10);
}
}Here's a list of all currently implemented constraint types:
NotNullConstraintfor arbitrary reference types;NotNullOrEmptyConstraintfor strings;NotNullOrWhitespaceConstraintfor strings;RangeConstraint,LessConstraint,LessOrEqualConstraint,GreaterConstraintandGreaterOrEqualConstraintfor any types that implementIComparable;UniqueConstraintto check that a set of field/properties only contains unique values;
Related pages
Obtain settings from providerBinding nodes to modelsLast updated
Was this helpful?