Validating MVC Force jQuery for a group of elements

My form, which I am developing with MVC 4, has several DIVS with many elements in each of them. My goal is to open / close DIVS when the user fills in the fields. However, I want to use an unobtrusive check on every DIV, not the whole form. Is this possible without checking each item separately? Maybe use a div id or something else? I do not want to create this massive function to check each element in each DIV so that the user can move on to the next DIV.

I am trying to do this and it does not work:

 var elems = [];
 var valid = true;
 ("#Contact").find('.text_input').each(function() {
    elems.push(this.id);
  }
  for (var i = 0; i<= elems.length; i++) {
       if ($("#" + elems[i]) != undefined) {
           $("#form1").validate().element("#" + elems[i]))
           if ($("#" + elems[i]).valid()) {
           }
           else {
             valid = false;
           }
        }
   }

but I keep getting undefined error. Elements in the DIV that have the text_input class are those that are needed for validation.

+4
1

, Validator.element(element) - . , ( views html, )

  • div - . var controls = $(this).closest('div').find('input, textarea, select');
  • $.each $("form").validate().element($(this));
  • , $(this).valid();
  • , div

( )

<div class="section">
  <h2>Section 1</h2>
  .... // Your inputs and validation
    @Html.LabelFor(m => m.SomeProperty)
    @Html.TextBoxFor(m => m.SomeProperty)
    @Html.ValidationMessageFor(m => m.SomeProperty)
  <div class="error"></div>
  <button type="button" class="next">Next</button>
</div>
<div class="section">
  <h2>Section 2</h2>
  .... // Your inputs and validation
  <div class="error"></div>
  <button type="button" class="next">Next</button>
</div>
<div class="section">
  <h2>Section 3</h2>
  .... // Your inputs and validation
  <div class="error"></div>
  <button type="submit" class="next">Submit</button> // submit button for last section
</div>

CSS

.section:not(:first-of-type) {
    display:none;
}

Script

$('button').click(function () {
  var container = $(this).closest('.section');
  var isValid = true;     
  $.each(container.find('input'), function () {
    $('form').validate().element($(this));
    if (!$(this).valid()) {
      isValid = false;
      return false;
    }
  });
  if (isValid) {
    container.next('.section').show().find('input').first().focus();
    container.hide();
  } else {
    container.find('.error').text('please complete');
  }
});
+6

All Articles