我正在使用FluentValidation,并且想要使用某些对象的属性值来格式化消息。问题是我对C#中的表达式和委托(delegate)的经验很少。
FluentValidation已经提供了一种使用format参数的方法。
RuleFor(x => x.Name).NotEmpty()
.WithMessage("The name {1} is not valid for Id {0}", x => x.Id, x => x.Name);
我想做这样的事情,以避免在更改参数顺序时不必更改消息字符串。
RuleFor(x => x.Name).NotEmpty()
.WithMessage("The name {Name} is not valid for Id {Id}",
x => new
{
Id = x.Id,
Name = x.Name
});
原始方法签名如下所示:
public static IRuleBuilderOptions<T, TProperty> WithMessage<T, TProperty>(
this IRuleBuilderOptions<T, TProperty> rule, string errorMessage,
params Func<T, object>[] funcs)
我正在考虑为该方法提供Func列表。
有人可以帮我吗?
最佳答案
您不能使用FluentValidation中的WithMessage来执行此操作,但是可以高举CustomState属性并将其注入(inject)那里。这是一个工作示例;您的另一个选择是派生FluentValidation并为WithMethod进行其他重载。
这是一个控制台应用程序,引用了Nuget的FluentValidation和此博客文章的JamesFormater:
http://haacked.com/archive/2009/01/04/fun-with-named-formats-string-parsing-and-edge-cases.aspx
最佳答案。从Ilya那里获得灵感,并意识到您可以搭载流利验证的扩展方法性质。因此,下面的方法不需要修改库中的任何内容。
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using FluentValidation;
namespace stackoverflow.fv
{
class Program
{
static void Main(string[] args)
{
var target = new My() { Id = "1", Name = "" };
var validator = new MyValidator();
var result = validator.Validate(target);
foreach (var error in result.Errors)
Console.WriteLine(error.ErrorMessage);
Console.ReadLine();
}
}
public class MyValidator : AbstractValidator<My>
{
public MyValidator()
{
RuleFor(x => x.Name).NotEmpty().WithNamedMessage("The name {Name} is not valid for Id {Id}");
}
}
public static class NamedMessageExtensions
{
public static IRuleBuilderOptions<T, TProperty> WithNamedMessage<T, TProperty>(
this IRuleBuilderOptions<T, TProperty> rule, string format)
{
return rule.WithMessage("{0}", x => format.JamesFormat(x));
}
}
public class My
{
public string Id { get; set; }
public string Name { get; set; }
}
public static class JamesFormatter
{
public static string JamesFormat(this string format, object source)
{
return FormatWith(format, null, source);
}
public static string FormatWith(this string format
, IFormatProvider provider, object source)
{
if (format == null)
throw new ArgumentNullException("format");
List<object> values = new List<object>();
string rewrittenFormat = Regex.Replace(format,
@"(?<start>\{)+(?<property>[\w\.\[\]]+)(?<format>:[^}]+)?(?<end>\})+",
delegate(Match m)
{
Group startGroup = m.Groups["start"];
Group propertyGroup = m.Groups["property"];
Group formatGroup = m.Groups["format"];
Group endGroup = m.Groups["end"];
values.Add((propertyGroup.Value == "0")
? source
: Eval(source, propertyGroup.Value));
int openings = startGroup.Captures.Count;
int closings = endGroup.Captures.Count;
return openings > closings || openings % 2 == 0
? m.Value
: new string('{', openings) + (values.Count - 1)
+ formatGroup.Value
+ new string('}', closings);
},
RegexOptions.Compiled
| RegexOptions.CultureInvariant
| RegexOptions.IgnoreCase);
return string.Format(provider, rewrittenFormat, values.ToArray());
}
private static object Eval(object source, string expression)
{
try
{
return DataBinder.Eval(source, expression);
}
catch (HttpException e)
{
throw new FormatException(null, e);
}
}
}
}