I have a client that requires two buttons on the form. One that saves the progress of an uncompleted form. So this form will still need to validate the fields but will just ignore the required validation. The other button will need to run the complete validation included required fields.
I am using the stock standard asp.net core project which I believe uses jquery-validation-unobtrusive and is based on the model for the view.
What I am trying to do is when the "Save Progress" button is clicked to remove all the required validation and submit the form. However none of the code that I have found on stack overflow or the internet works for my scenario.
I have tried:
<div class="form-group">
<input id="Progress" type="submit" value="Save Progress" onclick="foo()" class="btn btn-default" />
</div>
function foo() {
$('#FamilyName').rules("remove", "required");
return true
}
and
function foo() {
var settings = $('#Registration').validate().settings;
for (var i in settings.rules) {
delete settings.rules[i].required;
}
}
both of the above two attempts successfully find and remove rules but when the form is submitted validation still fails for the field in question.
I am stumped and not sure how to proceed.
Changing the required
rule(s) on the client does not affect server side validation. Your [Required]
attribute validation is still executed during the model binding process, therefore ModelState
will be invalid, and you would manually need to check each property to determine if its invalid because of a [Required]
attribute, or because of one of your other validation attributes.
In addition, you will need to add all the rules back again (or re-parse the $.validator
) to get the client side validation for your normal submit.
Instead, include a bool
property in your view model, so that you can use a conditional [RequiredIf]
attribute (you could use a foolproof attribute, or the one in this project).
Your model would then include
public bool IsDraft { get; set; }
[RequiredIf("IsDraft", false, ErrorMessage = "...")]
public string FamilyName { get; set; }
and in the view
@Html.HiddenFor(m => m.IsDraft)
@Html.LabelFor(m => m.FamilyName)
@Html.TextBoxFor(m => m.FamilyName)
@Html.ValidationMessageFor(m => m.FamilyName)
<input id="Progress" type="button" value="Save Progress" class="btn btn-default" />
<input id="Final" type="button" value="Save Final" class="btn btn-default" />
and the associated scripts
$('#Progress').click(function() {
$('#IsDraft').val('True');
$(yourForm).submit();
});
$('#Final').click(function() {
$('#IsDraft').val('False');
$(yourForm).submit();
});