使用mvc客户端验证的动态控件

时间:2011-05-11 13:55:38

标签: asp.net-mvc-2 client-side-validation

我有一个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的{​​{1}}方法,它会忽略任何其他验证定义。不知何故,我需要将我的验证注入大验证字段定义。这样当调用MicrosoftMvcJQueryValidation.cs时,所有这些都会立即注册。

1 个答案:

答案 0 :(得分: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"
});
//]]>

<% } %>