2011-05-11 65 views
0

我有一個MVC 2應用程序,我正在使用客戶端驗證。表單的一部分是從數據庫動態構建的字段。我也想允許客戶端驗證任何應該是總計字段(數字)的字段。使用mvc客戶端驗證的動態控件

所以,我把驗證碼的大斑點,並內置一個匹配的語句

//<![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被調用時,它們全部被立即註冊。

回答

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" 
}); 
//]]> 

<% } %> 
+0

你也可以這樣做:http://stackoverflow.com/questions/13379339/how-to-add-a-new-validation-rule-to-mvcclientvalidationmetadata – 2012-11-14 13:14:29