3

首先我想说的是,这个站点对于快速掌握 MVC 和 DataAnnotations 非常有帮助。现在,进入问题。

首先,一些事实:我正在使用 MVC2 和 .NET 4.0 框架。更新到 MVC3 目前对我来说不是一个选项(这是我遇到的一半问题的最常见答案,但在这里可能并不重要)。

我创建了一个完全可用的自定义属性来验证数据库结果集中是否已经存在字符串。我还创建了匹配的自定义验证器和 javascript 来输出客户端元数据,它也可以工作。

我想解决的是如何覆盖客户端通过 jquery/javascript 使用的错误消息,而不是通过我的验证器。我希望客户端错误消息在输入字段无效时包含输入字段的值,这是无法通过验证器完成的。所以,一些代码:

验证器:

public class UniqueStringValidator : DataAnnotationsModelValidator<UniqueStringAttribute>
    {
        public UniqueStringValidator(ModelMetadata metadata, ControllerContext controllerContext,
                                    UniqueStringAttribute attribute)
            : base(metadata, controllerContext, attribute)
        {

        }

        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            //declare the services we'll need

            var rule = new ModelClientValidationRule
            {
                ValidationType = "uniquestring",
                ErrorMessage = "The string is not unique.", //I want to override this on the client, but NOT HERE
            };

            //This is how I pull additional attributes from the viewmodel in MVC2 (wish I was on MVC3)
            //"c" represents the current record we're editing, if we're editing
            if (HttpContext.Current.Request.QueryString["c"] != null)
            {
                int id = Convert.ToInt32(HttpContext.Current.Request["c"]);
                string[] stringNames = //call a service and add some query to remove the current record from the results
                    //and return only the column of strings we're interested in

                rule.ValidationParameters.Add("stringlist", stringNames);
            }
            else
            //If we're here, we're not editing an existing record
            {
                string[] stringNames = //call a service and query only the column of interest
                rule.ValidationParameters.Add("stringlist", stringNames);
            }

            return new[] { rule };
        }
    }

这是我的 javascript 验证器:

    jQuery.validator.addMethod("uniquestring", function (value, element, params) {

    var stringNames = params.stringlist;

    for (var i = 0; i < stringNames .length; i++) {
        if (value == stringNames [i]) {
            //I want to override the error message here so I can include value
            return false;
        }
    }

    return true;
});

我重新审视了这一点,并尝试了更多的事情来真正理解发生了什么。错误消息设置在页面底部的元数据中,所有 javascript 函数似乎都能够确定验证是否应该通过或失败。使用 jquery 在函数末尾添加错误消息,甚至尝试将错误消息元素设置为 javascript 中的某些文本似乎没有什么不同或破坏脚本(我怀疑后一种方法“有效”但立即被元数据覆盖)。

有什么建议么?

4

1 回答 1

1

假设您使用的是 Microsoft 的不显眼验证,则确实为您设置了错误消息,并将覆盖您尝试在验证器中提供的消息。如果在创建 jquery 验证器时在选项中未指定任何消息,则您在验证器中提供的消息(通过 addMethod)是默认消息。

对于不显眼的验证,错误消息作为属性包含在正在验证的元素上(我没有 MVC2,但对于 3 和 4 是这样)

但是,您仍然可以手动覆盖此消息。

假设您的表单如下所示:

<form action="/controller/action" id="myForm" method="post">        
<input data-val="true" data-val-uniquestring="The string is not unique" type="text" name="foo" id="foo"/>
    <div data-valmsg-for="foo"></div>
    <button type="submit">Ok</button>
</form>

您可以看到错误消息是在元素的属性中指定的,它将覆盖您在设置验证器时提供的默认错误消息。

要更改此消息的所有实例,您可以执行以下操作:

function myCustomMessage(ruleParams, element) {
    return $(element).val() + " is not a unique value";
}

// This snippet must come after the jquery.validate.unobtrusive.js file
$(function () {
    var settings = $("#myForm").validate().settings;

    for (var p in settings.messages) {
        if (typeof settings.messages[p]["uniquestring"] !== "undefined") {
            settings.messages[p]["uniquestring"] = myCustomMessage;
        }
    }

});
于 2013-11-18T04:40:46.560 回答