Using FluentValidation's WithMessage method with a list of named parameters

后端 未结 5 650
长发绾君心
长发绾君心 2021-02-07 04:57

I am using FluentValidation and I want to format a message with some of the object\'s properties value. The problem is I have very little experience with expressions and delegat

5条回答
  •  爱一瞬间的悲伤
    2021-02-07 05:48

    While KhalidAbuhakmeh's answer is very good and deep, I just want to share a simple solution to this problem. If you afraid of positional arguments, why not to encapsulate error creation mechanism with concatenation operator + and to take advantage of WithMessage overload, that takes Func. This CustomerValudator

    public class CustomerValidator : AbstractValidator
    {
        public CustomerValidator()
        {
            RuleFor(customer => customer.Name).NotEmpty().WithMessage("{0}", CreateErrorMessage);
        }
    
        private string CreateErrorMessage(Customer c)
        {
            return "The name " + c.Name + " is not valid for Id " + c.Id;
        }
    }
    

    Prints correct original error message in next code snippet:

    var customer = new Customer() {Id = 1, Name = ""};
    var result = new CustomerValidator().Validate(customer);
    
    Console.WriteLine(result.Errors.First().ErrorMessage);
    

    Alternatively, use an inline lambda:

    public class CustomerValidator : AbstractValidator
    {
        public CustomerValidator()
        {
            RuleFor(customer => customer.Name)
                .NotEmpty()
                .WithMessage("{0}", c => "The name " + c.Name + " is not valid for Id " + c.Id);
        }
    }
    

提交回复
热议问题