ASP.NET MVC and partial client side validation

江枫思渺然 提交于 2019-12-13 03:45:27

问题


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');


来源:https://stackoverflow.com/questions/5992222/asp-net-mvc-and-partial-client-side-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!