2012-11-14 93 views
0

我有一個表單,需要兩個字段相同(密碼和密碼確認)。我創建了一個class屬性來檢查它,並在服務器端工作。在客戶端,它什麼都不做。我需要將信息顯示在ValidationSummary中(「密碼重複」需要與「密碼」相同)。如何將新的驗證規則添加到mvcClientValidationMetadata?

我意識到檢查這些字段的最簡單方法是手動將規則添加到window.mvcClientValidationMetadata。我試圖這樣做,但沒有奏效。

我的代碼:生成這種形式之前執行

<% using (Html.BeginForm("ResetPassword", "Account", FormMethod.Post})) 
    { %> 
<%= Html.ValidationSummary() %> 
    <div> 
     <%= Html.ValidationMessageFor(m => m.Email)%> 
     <%= Html.LabelFor(m => m.Email)%> 
    </div> 
    <div> 
     <%= Html.TextBoxFor(m => m.Email)%> 
     <% Html.ValidateFor(m => m.Email);%> 
    </div> 
    <div> 
     <%= Html.ValidationMessageFor(m => m.PasswordModel.Password)%> 
     <%= Html.LabelFor(m => m.PasswordModel.Password)%> 
    </div> 
    <div> 
     <%= Html.PasswordFor(m => m.PasswordModel.Password)%> 
    </div> 
    <div> 
     <%= Html.ValidationMessageFor(m => m.PasswordModel.PasswordRepeated)%> 
     <%= Html.LabelFor(m => m.PasswordModel.PasswordRepeated)%> 
    </div> 
    <div> 
     <%= Html.PasswordFor(m => m.PasswordModel.PasswordRepeated)%> 
    </div> 
    <div> 
     <%= Html.ValidationMessageFor(m => m.PasswordModel.PasswordRepeated)%> 
     <%= Html.LabelFor(m => m.PasswordModel.PasswordRepeated, true)%> 
    </div> 
<% } %> 

Html.EnableClientValidation方法。

下面你會發現我的問題的解決方案。

回答

0

您可能做的最糟糕的事情是執行完全相同的代碼 - 您會覆蓋現有的規則。

要添加您需要把這個代碼<% } %>關閉您的BeginForm的using(...之後的驗證規則:

<% } %> 

<script type="text/javascript"> 

    window.mvcClientValidationMetadata[0]["Fields"].push(//check if the '0' is number corresponding to your form validation metadata 
     { 
      "FieldName": "PasswordModel.PasswordRepeated", // name attribute of the element 
      "ReplaceValidationMessageContents": false, 
      "ValidationMessageId": "PasswordModel_PasswordRepeated_validationMessage", //id of the ValidationMessageFor (if needed) 
      "ValidationRules": 
      [ 
      { 
       "ErrorMessage": 'Password repeated needs to be the same as Password', 
       "ValidationParameters": "#PasswordModel_Password", //'params' parameter in your validation function, can be an object 
       "ValidationType": "propertiesMustMatch" //name of the validation function placed in $.validator.methods 
      } 
      ] 
     } 
    ); 

</script> 

propertiesMustMatch功能檢查,如果給定的字段相等(jQuery的equalTo didin't在我們的系統中正常工作) 。

沒有「Uncaught TypeError:Can not call method'push'of undefined」exception,因爲在<script>元素中生成了mvcClientValidationMetadata,其中<% } %>是。