MVC3客户端验证JS格式错误消息自动?

时间:2012-02-22 21:55:30

标签: asp.net-mvc-3 unobtrusive-validation client-side-validation

我使用以下示例JS代码创建了自定义验证:

(function ($) {
    $.validator.unobtrusive.adapters.add('myrule', ['minvalueproperty', 'maxvalueproperty'],
        function (options) {
            options.rules['myrule'] = options.params;
            options.messages['currencyrule'] = options.message;
        }
    );

    $.validator.addMethod('myrule', function (value, element, params) {
        return false;
    }
} (jQuery));

服务器端验证器代码是

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class MyValidationAttribute : ValidationAttribute, IClientValidatable
{
    public CurrencyValidationAttribute(string minPropertyName, string maxPropertyName)
        : base (DefaultErrorMessage)
    {
        this.minPropertyName = minPropertyName;
        this.maxPropertyName = maxPropertyName;
    }
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        return new ValidationResult(this.ErrorMessage);
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var clientValidationRule = new ModelClientValidationRule
        {
            ValidationType = "myrule",
            ErrorMessage = this.ErrorMessage,
        };
        clientValidationRule.ValidationParameters["minvalueproperty"] = minPropertyName;
        clientValidationRule.ValidationParameters["maxvalueproperty"] = maxPropertyName;
        yield return clientValidationRule;
    }
}

我的模型类使用自定义验证属性

进行修饰
    [MyValidation("MinValue", "MaxValue",
        ErrorMessage = "Wrong value, must be between {0} and {1}")]
    public string Money { get; set; }

除了显示错误消息之外,它似乎适用于大多数部分。在我的模型属性中,我使用了一个带有占位符的字符串来替换它,但是还没有实际的代码。

当我运行页面时,我在文本框中输入了一些无效值,并强制客户端验证返回false,有趣的是我看到的错误消息是

  

错误的值必须介于[object Object]和{1}

之间

不知何故{0}被自动替换。任何线索是什么原因导致错误消息被替换?

0 个答案:

没有答案