MVC Force jQuery validation on group of elements

后端 未结 1 1330
北恋
北恋 2020-11-22 11:50

My form I am designing with MVC 4 has mutiple DIVS with many elements in each one. My objective is to open/close DIVS as the user completes the fields. However, I want to

相关标签:
1条回答
  • 2020-11-22 12:06

    You can validate individual controls using Validator.element(element) - see documentation here, so you could use the following approach (you haven't posted the views html so can't write the actual code for you)

    In the Next button click event

    1. Select all the the controls within the associated div - e.g. var controls = $(this).closest('div').find('input, textarea, select');
    2. In an $.each loop, call $("form").validate().element($(this));
    3. If necessary, test if valid with $(this).valid();
    4. If everything is valid, hide the current div and display the next

    Edit (example added)

    View

    <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');
      }
    });
    
    0 讨论(0)
提交回复
热议问题