I have a mvc form where users can add dynamic elements. I am using unobstrusive validation with MVC. I also have two buttons, one save as draft and the other submit. The submit button correctly triggers the validation including the dynamic elements that were added.
However i am having a hard time trying to clear validation attributes data-val-* on the client side if save as draft is clicked.
Whatever i do, i can never trigger form submit to call my action method. Obviously only then i could handle disabling the server side validation.
I have tried the following
$("#myform").submit(function () {
---
//some code to check which submit button was clicked
//if save as draft was clicked, proceed below
---
var settings = $("#myform").validate().settings;
for (var ruleIndex in settings.rules) {
delete settings.rules[ruleIndex];
$('#myform').clearErrors();
//$("#myform").removeData("validator")
// .removeData("unobtrusiveValidation");
$("select").removeAttr("data-val-required");
$("select").removeAttr("data-val-number");
$("input").removeAttr("data-val-required");
if ($("#myform").valid()) {
alert("valid"); //I can reach here indicating that the form is valid at this point.But still my action method is not called.
}
}
$.fn.clearErrors = function () {
$(this).each(function () {
$(this).find(".field-validation-error").empty();
$(this).find(".input-validation-error").removeClass("input-validation-error");
$(this).trigger('reset.unobtrusiveValidation');
});
};
Try to add formnovalidate attribute on your "save as draft" button as described in Documentation for jqueryvalidation.
Example :
<input type="submit" formnovalidate name="saveAsDraft" value="Cancel">
You might have to use class="cancel" attribute instead of formnovalidate attribute in case you are on a older version . Example :
<input type="submit" class="cancel" name="saveAsDraft" value="Cancel">