Interface ICommandValidator<TCommand, TModel>
- Namespace
- Dynamicweb.CoreUI.Data
- Assembly
- Dynamicweb.CoreUI.dll
Validates the model carried by TCommand before its
ICommandHandler<TCommand, TModel> runs.
public interface ICommandValidator<in TCommand, in TModel> where TCommand : CommandBase<in TModel> where TModel : new()
Type Parameters
TCommandThe command type this validator applies to.
TModelThe model carried by the command.
Remarks
Replaces overriding ValidateModel(T): keeps validation out of the command, which then holds data only, and lets the validator take its dependencies through the constructor.
No dependency registration is required; discovery is handled internally. Implementations are expected to be internal and sealed.
Unlike handlers, a command may have any number of validators - every one of them runs and their results are combined. Returning no results means the model is valid.
using System.Collections.Generic;
using Dynamicweb.CoreUI.Data;
using Dynamicweb.CoreUI.Data.Validation;
using Dynamicweb.Ecommerce.Orders;
using Dynamicweb.Examples.UI.Models;
namespace Dynamicweb.Examples.UI.Commands;
/// <summary>
/// Example of an <see cref="ICommandValidator{TCommand, TModel}"/> - where validation lives now that
/// <see cref="Command{T}.ValidateModel"/> is sealed.
/// </summary>
/// <remarks>
/// Shows both kinds of rule: one that only needs the model, and one that needs a service. The service arrives through
/// the constructor, which an override on the command could never have done. A command may have any number of
/// validators; every one of them runs and their results are combined.
/// </remarks>
/// <param name="orderService">Used to check whether the order may still be changed.</param>
internal sealed class OrderChangeExampleCommandValidator(OrderService orderService) : ICommandValidator<OrderChangeExampleCommand, OrderChangeExampleDataModel>
{
/// <inheritdoc />
public IEnumerable<ValidationResult> Validate(OrderChangeExampleCommand command, OrderChangeExampleDataModel model)
{
if (string.IsNullOrWhiteSpace(model.CustomerName))
yield return new(nameof(model.CustomerName), "A customer name is required");
if (orderService.IsComplete(model.OrderId))
yield return new(nameof(model.Comment), "A completed order cannot be changed");
}
}
Methods
Validate(TCommand, TModel)
Validates model and returns one result per problem found.
IEnumerable<ValidationResult> Validate(TCommand command, TModel model)
Parameters
commandTCommandThe command carrying the model.
modelTModelThe model to validate.