I have a tabbed panel like below:
Student tab has StudentName and Mark tabs has Math. This is my Model:
public class StudentViewModel
{
[Required]
public string StudentName { get; set; }
[Required]
public int Math { get; set; }
}
This is the View for the above tabbed panel:
<form action="~/Controller/Action" method="Post" id="myFormId">
<div class="panel-body">
<div class="tab-content">
<div class="tab-pane active" id="Student">
@Html.EditorFor(m => m.StudentName)
@Html.ValidationMessageFor(m => m.StudentName)
</div>
<div class="tab-pane" id="Mark">
@Html.EditorFor(m => m.Math)
@Html.ValidationMessageFor(m => m.Math)
</div>
</div>
</div>
<input type="submit" value="Submit" class="btn btn-success" />
</form>
The entire tabbed panel is inside 1 form and I am using jQuery.Validate to validate the form when user submits the form.
What I want is to switch to Mark tab, if there is a validation message on Math field and there is no error on Student name. What is the best approach to achieve this using jQuery.Validate?
One option would be to test if the form is valid, and if not, find the <span>
elements generated by @Html.ValidationMessageFor()
and check if they contain the field-validation-error
class. If so, switch to its parent <div class="tab-pane">
element.
I am assuming that your tabs actually contain multiple form controls (if not, then you could probably simplify the following)
var tabs = $('.tab-pane'); // get all the tabs
$('#myFormId').submit(function() {
if(!$(this).valid()) { // check if the form is valid
$.each(tabs, function(index, item) {
// Test if any errors for form controls in the tab
if($(this).find('.field-validation-error').length > 0) {
// Change the active tab
tabs.removeClass('active');
$(this).addClass('active');
return false; // exit the $.each() loop
}
});
}
});
Note that the above code will activate the first tab containing invalid controls.
Another option would be to use the Validator.element(element)
function as described in MVC Force jQuery validation on group of elements, although that is probably more appropriate code to run when you switch between tabs (i.e. to prevent moving to another tab if there are validation errors on the current tab)