我正在尝试将NotEqual客户端规则添加到找到的here的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;
}
}
答案 0 :(得分:0)
更改
var errorMessage = new MessageFormatter().BuildMessage(validator.ErrorMessageSource.GetString());
到
var formatter = new MessageFormatter().AppendPropertyName(Rule.PropertyName);
string errorMessage = formatter.BuildMessage(validator.Options.ErrorMessageSource.GetString(null));
让我了解了我在验证规则中设置的错误消息。