Skip to content Skip to sidebar Skip to footer

How To Add A New Validation Rule To Mvcclientvalidationmetadata?

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 cli

Solution 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:

<% } %>

<scripttype="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.

Post a Comment for "How To Add A New Validation Rule To Mvcclientvalidationmetadata?"