我正在尝试将不平等客户端规则添加到我的MVC 5项目中。
这一切似乎都在起作用,除了我似乎无法获取传递到规则中的错误消息。我可以在调试器的一个私有字段中看到它,我只是不确定如何在GetClientValidationRules
方法中获得它。问题在构建错误消息的线上,validator.ErrorMessageSource.GetString()
不再存在。
public class NotEqualClientRule : FluentValidationPropertyValidator
{
public static ModelValidator Create(ModelMetadata meta, ControllerContext context, PropertyRule propertyDescription, IPropertyValidator validator)
{
return new NotEqualClientRule(meta, context, propertyDescription, validator);
}
public NotEqualClientRule(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule propertyDescription, IPropertyValidator validator) : base(metadata, controllerContext, propertyDescription, validator)
{
ShouldValidate = false; //This is necessary - don't want to kick in during model binding.
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
if (!this.ShouldGenerateClientSideRules())
{
yield break;
}
var validator = Validator as NotEqualValidator;
var errorMessage = new MessageFormatter()
.BuildMessage(validator.ErrorMessageSource.GetString());
var rule = new ModelClientValidationRule
{
ErrorMessage = errorMessage,
ValidationType = "notequal"
};
if (validator.MemberToCompare != null)
{
rule.ValidationParameters["field"] = String.Format("#{0}", validator.MemberToCompare.Name);
}
else
{
rule.ValidationParameters["field"] = validator.ValueToCompare;
}
yield return rule;
}
}
更改
var errorMessage = new MessageFormatter().BuildMessage(validator.ErrorMessageSource.GetString());
to
var formatter = new MessageFormatter().AppendPropertyName(Rule.PropertyName);
string errorMessage = formatter.BuildMessage(validator.Options.ErrorMessageSource.GetString(null));
给我我在验证规则中设置的错误消息。