0

我有一个 MVC 2 应用程序,并且正在使用客户端验证。表单有一部分字段是从数据库动态构建的。我还想允许客户端验证任何应该是总计字段(数字)的字段。

所以,我拿了一大堆验证代码并构建了一个匹配语句

//<![CDATA[
if (!window.mvcClientValidationMetadata) { window.mvcClientValidationMetadata = []; }
window.mvcClientValidationMetadata.push({ "Fields":
        [{ "FieldName": "<%= id %>", "ReplaceValidationMessageContents": true, "ValidationMessageId": "<%= id %>_validationMessage", "ValidationRules":
            [{ "ErrorMessage": "You must enter an <%= id %>", "ValidationParameters": {}, "ValidationType": "required" },
                { "ErrorMessage": "The <%= id %> must be more than $0.00", "ValidationParameters": { "minimum": 0.01, "maximum": 1.7976931348623157E+308 }, "ValidationType": "range" },
                { "ErrorMessage": "The field <%= id %> must be a number.", "ValidationParameters": {}, "ValidationType": "number" }
        ]}], "FormId": "new-creditcard-form", "ReplaceValidationSummary": false, "ValidationSummaryId": "CreditCardSummary"
});

//]]>

这不会导致错误。但是,当页面加载时,仅显示由我的数据注释/控件生成的验证。我假设错误是我的验证被推送到堆栈上,服务器生成的验证是堆栈上的最后一个,并且只有一个项目用于验证,最后一个打开/第一个关闭。

有什么想法可以让它正常工作吗?

编辑:

我发现,如果我在构建验证字段后立即调用__MVC_EnableClientValidation驻留在其中的方法,它会忽略任何其他验证定义。MicrosoftMvcJQueryValidation.cs不知何故,我需要将我的验证注入到大验证字段定义中。这样当__MVC_EnableClientValidation被调用时,它们都会立即注册。

4

1 回答 1

0

我想通了。我需要使用splice而不是push

<% if (Model.HasCustomValidation) { %>
//<![CDATA[
if (!window.mvcClientValidationMetadata) { window.mvcClientValidationMetadata = []; }
window.mvcClientValidationMetadata.splice(0,0,{ "Fields":
        [{ "FieldName": "<%= id %>", "ReplaceValidationMessageContents": true, "ValidationMessageId": "<%= id %>_validationMessage", "ValidationRules":
            [
                <% if (Model.EnableTotalledValidation) { %>
                    { "ErrorMessage": "The <%= Model.Column.Name %> in row <%= Model.RowNumber %> cannot be empty.", "ValidationParameters": {}, "ValidationType": "required" },
                    { "ErrorMessage": "The <%= Model.Column.Name %> in row <%= Model.RowNumber %> must be a number.", "ValidationParameters": {}, "ValidationType": "number" }
                <% } %>

                <% if(Model.EnableTotalledValidation && (Model.EnableRegexValidation || Model.EnableLengthValidation)) { %>
                    ,
                <% } %>

                <% if(Model.EnableRegexValidation) { %>
                    {"ErrorMessage":"<%: Model.Column.ClientSideRegexErrorMessage %>","ValidationParameters":{"pattern":"<%: Model.Column.ClientSideRegex %>"},"ValidationType":"regularExpression"}
                <% } %>
            ]
        }], "FormId": "new-creditcard-form", "ReplaceValidationSummary": false, "ValidationSummaryId": "CreditCardSummary"
});
//]]>

<% } %>
于 2011-05-19T14:50:53.810 回答