SNT
SNT

Reputation: 313

C# No validation when Hidden Field

The following code should ignore any validation fields with the class ignore

With the HTML helper I added the class ignore, but whenever I press submit it will still want validation, even though the class ignore is added.

According to: jQuery disable rule validation on a single field The following jQuery should disable any validation on fields with the class ignore however that does not work.

jQuery

function hideBel() {
    $('#BelBep').hide();
    $('#iqform').validate(
       { ignore: ".ignore, :hidden"
    })
};

create.cshtml

<fieldset id="iqform">
    <legend>Form</legend>
    <div class="editor-label">@Html.LabelFor(model => model.BevBeleid) @Html.ValidationMessageFor(model => model.BevBeleid)</div>
    <label>@Html.RadioButtonFor(model => model.BevBeleid, "true", new { onclick = "showBel();"}) Ja</label>
    <label>@Html.RadioButtonFor(model => model.BevBeleid, "false", new { onclick = "hideBel();" }) Nee</label>

    <div id="BelBep" style="display: none;">
        <div class="editor-label">@Html.LabelFor(model => model.BelLastName)</div>
        <div class="editor-field">
            @Html.EditorFor(model => model.BelLastName, new { htmlAttributes = new {@class = "ignore"}})
            @Html.ValidationMessageFor(model => model.BelLastName)
        </div>

    </fieldset>

Upvotes: 0

Views: 982

Answers (1)

Koti Panga
Koti Panga

Reputation: 3720

To achieve this ignore behavior we should add required selectors to jQuery-validation-defaults.
As we know :hidden is by default, here we're adding .ignore CssClass selector as shown below.

How and where this defaults script should place in the code file.

I'm doing like below in myview.cshtml file

<!--HTML and Razor markup -->
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")

    <script>
        //Below defaults setting should run 
        //after jquery.validation js execution and before DOM-Ready.
        //Note: This script block placement must be after below script embed tags
        //jquery.validate.min.js,jquery.validate.unobtrusive.min.js(=>jqueryval bundle)
        $.validator.setDefaults({
            ignore: ':hidden, .ignore'
        });
        $(function () {
            //Script to Run after DOM-Ready
        });
    </script>
} 

Upvotes: 1

Related Questions