I created a validation behaivor but this doesn't show error to user in view. Instead it throws a validation exception in Visual Studio. How can I show errors to the user in view?
public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
private readonly IEnumerable<IValidator<TRequest>> _validators;
public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
{
_validators = validators;
}
public Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
var context = new ValidationContext<TRequest>(request);
var failures = _validators
.Select(x => x.Validate(context))
.SelectMany(x => x.Errors)
.Where(x=>x !=null)
.ToList();
if (failures.Any())
{
throw new ValidationException(failures);
}
return next();
}
}
public class SaveXValidator : AbstractValidator<SaveXCommand>
{
public SaveXValidator()
{
RuleFor(x=>x.ImageUrl).NotEmpty().WithMessage("Can't be empty!");
RuleFor(b => b.StartDate)
.LessThan(p => p.CreatedDate).WithMessage("error example");
}
}