Skip to content

Separate validation classes and validator factory

Vsevolod Pilipenko edited this page Jul 19, 2022 · 4 revisions

Create and use separate class with validation rules

Just create class and inherit it from ValidationRuleBuilder<TYourViewModel> and create rules in constructor:

public class YourViewModelValidation : ValidationRuleBuilder<YourViewModel>
{
    public YourViewModelValidation()
    {
        RuleFor(vm => vm.Name)
            .NotEmpty()
            .MaxLength(16)
            .NotEqual("foo");

        RuleFor(vm => vm.Surname)
            .Equal("foo");

        RuleFor(vm => vm.PhoneNumber)
            .NotEmpty(ValidationMessageType.Warning)
            .Matches(@"^\d{9,12}$");
    }
}

In constructor of YourViewModel you can create validator for it:

Validator = new YourViewModelValidation().Build(this);

Register rule builder classes

You also can register such classes in the factory and create it dynamically. Sample with Dependency Injection:

public YourViewModel(IValidatorFactory validatorFactory)
{
    Validator = validatorFactory.GetValidator(this);
}

or with static reference:

public YourViewModel(IValidatorFactory validatorFactory)
{
    Validator = ValidationOptions.ValidatorFactory.GetValidator(this);
}

If your use DI at your application, first way is better.

But before using you have to configure factory. You can do it with ValidationOptions like this:

ValidationOptions
    .Setup()
    .RegisterForValidatorFactory(new YourViewModelValidation());

There are four overloading of method RegisterForValidatorFactory:

RegisterForValidatorFactory(IObjectValidatorBuilderCreator creator);
RegisterForValidatorFactory(IEnumerable<IObjectValidatorBuilderCreator> creators);
RegisterForValidatorFactory(Assembly assembly, Func<Type, IObjectValidatorBuilderCreator>? factoryMethod = null);
RegisterForValidatorFactory(IEnumerable<Assembly> assemblies, Func<Type, IObjectValidatorBuilderCreator>? factoryMethod = null);

First two allows you to create and specify objects by yourself. Last two allows you to specify assembly/assemblies where you are storing classes with validation rules. If you don't specify factoryMethod, they have to have parameterless constructor.

Create custom validator factory

You also can create your own validator factory. For this your class has to implement interface ReactiveValidation.ValidatorFactory.IValidatorFactory. For setup class use:

ValidationOptions
    .Setup()
    .UseCustomValidatorFactory(YourValidatorFactory);

Note: You can't use methods RegisterForValidatorFactory with your own class. You should specify classes with rules by yourself.