MVC : How to enable client side validation on hidden fields

RollerCosta picture RollerCosta · Jul 4, 2014 · Viewed 24.2k times · Source

@Scripts

 <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")"></script>
  <script src="@Url.Content("~/Scripts/jquery.validate.js")"></script>
  <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")"></script>

@View

@using (Html.BeginForm("TestModelState", "RandD", FormMethod.Post, new {id="form123" }))
{ 
    @Html.TextBoxFor(x => x.htmlText, new { style="display:none"})<br />
    @Html.ValidationMessageFor(x => x.htmlText)
    <div>
      @Html.TextBoxFor(x => x.Uprop1)<br />
      @Html.ValidationMessageFor(x => x.Uprop1)
    </div>
    <input type="submit" value-="Submit" onclick="abc()" />
}

WHAT I have tried

  1. Replaced ignore: ":hidden", with ignore: "", inside validate.js
  2. var validateMeta = $('#form123').validate(); validateMeta.settings.ignore = "";

  3. $.validator.setDefaults({ignore: ""});

  4. $.validator.setDefaults({ ignore: [] });

Answer

Robin Hames picture Robin Hames · Jul 15, 2014

I ran into this same problem. A hidden field on a page was storing a user ID, which was selected from an autocomplete text box. This ID had validation to ensure that a non-zero id was posted back. We wanted to include this validation in the client side.

By default jQuery validate ignores hidden fields, elements with zero width and height, those with css display:none and any elements with an invisible parent (using same criteria).

The ignore setting can however be overridden by adding the following script (I just added it to my custom validator script before calling $.validator.addMethod()):

// By default validator ignores hidden fields.
// change the setting here to ignore nothing
$.validator.setDefaults({ ignore: null });

NOTE: This code won't work if it's run inside the document ready or jQuery $(function () {}) method.