MVC Validation with JQuery Accordion

2019-07-23 10:24发布

I am relatively new to ASP.NET MVC but am really impressed by the validation features. I have a giant form that I have split into an accordion using JQuery UI. This form is a very basic scaffold of a model and that model has code like the following to validate each field that is required:

    [Required(ErrorMessage="Please Enter a Valid Product")]
    [DisplayFormat(ConvertEmptyStringToNull= false)]
    [StringLength(160, MinimumLength=2,ErrorMessage="Product Must Be At Least 2 Characters")]

and then the view simply has:

            <div class="editor-label">
                @Html.LabelFor(model => model.Product)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Product)
                @Html.ValidationMessageFor(model => model.Product)
            </div>

That works great if that field is being viewed in the accordion. If you leave the field blank, the messages shows up and everything works as planned. Problem is, when I switch to a different tab in the accordion, and the required field isn't visible, I can submit the form just fine, much to the dismay of my server. If I fill out the field, it is passed as expected of course. Is there a way to get around this?

1条回答
我只想做你的唯一
2楼-- · 2019-07-23 10:59

Turns out the answer was to put the following into the view:

$('#Form').validate().settings.ignore = []

The issue was that hidden fields are not checked using Jquery validation (which is what MVC uses) and once an accordian collapses they are hidden. This tells them not to ignore them.

查看更多
登录 后发表回答