Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I enable/disable unobtrusive validation on show/hide via jquery?
    text
    copied!<p>Update: What I'm asking is whether it's possible to remove validation rules which are inferred from Attributes on fields in my viewmodel, on the client side ONLY.</p> <p>--</p> <p>I am toggling the display of certain fields when a choice is made from a dropdown list. I need to also toggle the validation.</p> <p>ViewModel.cs:</p> <pre><code>public int ddlTypeID { get; set; } public Dictionary&lt;int, string&gt; ddlTypes { get; set; } [Required(ErrorMessageResourceName = "msgRequired", ErrorMessageResourceType = typeof(Resources.Globals))] public DateTime firstDate {get; set;} [Required(ErrorMessageResourceName = "msgRequired", ErrorMessageResourceType = typeof(Resources.Globals))] public DateTime otherDate {get; set;} </code></pre> <p>Create.cshtml:</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function () { $('.optional').hide(); $('#ddlTypeID').change(function () { var id = $(this).val(); if (id == 1) { $('.optional').show(); } else { $('.optional').hide(); } }); }); &lt;/script&gt; @using (Html.BeginForm()) { &lt;div class="editor-field"&gt; @Html.DropDownListFor(x=&gt;x.ddlTypeID, new SelectList(Model.ddlTypes,"Key","Value",Model.ddlTypeID),Resources.Globals.msgType) @Html.ValidationMessageFor(model =&gt; model.ddlTypeID) &lt;/div&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.firstDate ) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.EditorFor(model =&gt; model.firstDate ) @Html.ValidationMessageFor(model =&gt; model.firstDate ) &lt;/div&gt; &lt;div class="editor-label optional"&gt; @Html.LabelFor(model =&gt; model.otherDate ) &lt;/div&gt; &lt;div class="editor-field optional"&gt; @Html.EditorFor(model =&gt; model.otherDate ) @Html.ValidationMessageFor(model =&gt; model.otherDate ) &lt;/div&gt; &lt;input type="submit" value="Save" /&gt; } </code></pre> <p>This works to hide/show the fields for otherDate - but how can I toggle the validation at the same time? Or is there a better way to do this?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload