问题
I have a form with two fields that need to be equal (password and password confirmation). I've created a class attribute to check that and on server side it works great. On the client side it does nothing. I need the message to appear in ValidationSummary ("Password repeated" needs to be the same as "Password").
I realized that the easiest way to check these fields would be adding the rule manually to window.mvcClientValidationMetadata. I was trying to do that but nothing worked.
My code:
<% 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
method is executed before this form is generated.
Below you'll find the solution to my problem.
回答1:
The worst thing you may do is to execute exacly the same code - you'll overwrite the existing rules.
To add validation rules you need to put this code right after <% } %>
closing using(...
of your BeginForm:
<% } %>
<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 function checks if given fields are equal (jQuery equalTo didin't work correctly in our system).
There is no "Uncaught TypeError: Cannot call method 'push' of undefined" exception, because mvcClientValidationMetadata is generated in <script>
element put where <% } %>
is.
来源:https://stackoverflow.com/questions/13379339/how-to-add-a-new-validation-rule-to-mvcclientvalidationmetadata