ASP.NET MVC and partial client side validation

2019-08-30 19:24发布

问题:

I have huge form that I'd like to split in different steps, but I need to validate the fields in the current step before go to the next step.

E.g.: My form has 40 fields, and they are divided in 4 steps (10 fields each). In the HTML the 40 are in the same page, but with jQuery I only show the first 10 and a next button, the fourth page contains the "Submit" button. I need a way to invoke the validation of those ten fields before go to the next step.

Is there any way to accomplish this?

Regards.

回答1:

If you are using buttons to move between each step, you can revise your page to have a separate form for each step. You then may limit validation to the form which is the parent of the submit button, and use the validation for the "step" to determine whether to enable/show the form for the next step. Here is some example code:

$(".stepButton").live("click", function() {
    if (isValid(this)) {
        // code to proceed to next step
    }
});

function isValid(el) {
    var $thisform = $(el).parent().parent();
    $thisform.validate();
    return $thisform.valid();
}


回答2:

Assuming you use default mvc3 unobtrusive validation, you could call validation on desired elements with loop and Single Element Validation



回答3:

You could use the jQuery Validation plug-in. This has an option to ignore elements when validating. So you could, for instance, mark all the fields that are not shown (and don't require validating yet) with a class. For instance, to ignore all form elements with the class="ignore" you'd do this:

$("#myform").validate({
   ignore: ".ignore"
})


回答4:

Though ignoring elements by marking them with attribute class="ignore" works, MVC 3 uses jQuery's validation plug-in by default and that plug-in will not validate disabled fields. The code where you are hiding your elements besides visible 10 fields, you can just disable those elements as well and they won't be validated (and note that those disabled fields won't be posted to the server either).

e.g.

$('input').attr('disabled', 'disabled');