开发者

ASP.NET MVC and partial client side validation

开发者 https://www.devze.com 2023-03-05 22:26 出处:网络
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.

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开发者_C百科 to the next step.

Is there any way to accomplish this?

Regards.


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


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();
}


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"
})


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

精彩评论

暂无评论...
验证码 换一张
取 消