33

@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: [] });

Sparky
  • 98,165
  • 25
  • 199
  • 285
RollerCosta
  • 5,020
  • 9
  • 53
  • 71
  • Client side validation works if I remove "style="display:none" from htmlText text field . – RollerCosta Jul 04 '14 at 10:58
  • 2
    @Stilgar, you need to update your knowledge over MVC. – RollerCosta Jul 04 '14 at 11:14
  • 2
    @RollerCosta feel free to give me an update, not only on MVC but in general on why should you validate something that the user cannot possibly input. – Stilgar Jul 04 '14 at 11:17
  • 1
    Sure, I did not say that user can't enter value. Ex. If we are required to submit a form into two steps (step 1 contains n field and step 2 contains n field) with next and prev link and Submit button on step 2 – RollerCosta Jul 04 '14 at 11:23
  • @RollerCosta for that you can use partial views as well isnt it? – Arijit Mukherjee Jul 04 '14 at 11:32
  • No, I won't be able to tell you the entire scenario here and will appreciate If someone can tell me the solution of asked question. REASON why we cant use partial view : I have single Model/Entity to post and require all the corresponding details at once. – RollerCosta Jul 04 '14 at 11:34
  • I have used `$.validator.setDefaults({ ignore: "" });` with Required validation. What type of validation you are doing ? What is the jQuery Validation Plugin version you are using? – Saranga Jul 04 '14 at 12:39
  • The format is `ignore: []`. See [this](http://stackoverflow.com/a/8565769/594235) and then [this](http://stackoverflow.com/a/14506637/594235) – Sparky Jul 04 '14 at 14:33
  • 7
    There are certainly good reasons to validate a hidden field. For example, imagine a WYSIWYG HTML editor control that uses a hidden field to store the text content, while the UI is a separate set of controls. – FirstVertex Jan 05 '15 at 15:28
  • @IonutC's answer worked for me. In my case I wan getting user input from Popup and when I close my popup, application was not validatting any inputs. When i set 'ignore: ""' it worked. – Sandesh Daddi Mar 22 '15 at 14:37
  • Exactly my use case @FirstVertex – Auspex Nov 26 '21 at 14:54

5 Answers5

52

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.

James Hill
  • 60,353
  • 20
  • 145
  • 161
Nibor
  • 1,096
  • 8
  • 11
  • 2
    Just to add to this, you can also return a custom function (in place of null), which you can add conditions to if you're looking to only target certain hidden fields. – JDandChips Feb 15 '16 at 13:51
  • 1
    I recommend setting the value to ":disabled". – HasanG Apr 27 '17 at 21:53
  • 5
    It's worth noting that this doesn't work if it's called inside the `document ready` (or jQuery `$(function () {})`shortcut) function – James McCormack May 01 '17 at 18:44
  • Well played @JamesMcCormack this comment is super duper relevant and I got stuck on that for sometime. – Andrew Duffy Jul 08 '17 at 02:02
  • See also See also https://stackoverflow.com/a/38353576/292060 for for @DJandChips idea of conditions. – goodeye Jul 31 '19 at 22:35
  • It's worth noting that it WILL work if it's called inside `$(window).on('load', function () { ... })` function (instead of document load function as mentioned above) – Alexander Mihailov Aug 22 '22 at 16:04
16

Just after you insert the script for validation set the ignore to "":

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script type="text/javascript">
    $.validator.setDefaults({
        ignore: ""
    });
    </script>
}
IonutC
  • 607
  • 1
  • 6
  • 11
  • 9
    `$.validator.setDefaults({ ignore: "" });` didn't work for me, but `$.validator.setDefaults({ ignore: [] });` did. For reference, I'm using: ASP.NET MVC 5, Bootstrap 3.3.6, Kendo UI 2016.1.112, jQuery 1.9.1 (included with Kendo), jQuery Validation 1.14.0, and MS jQuery Unobtrusive Validation 3.2.2. – David Wilson Jan 29 '16 at 18:09
  • 5
    Also, make sure you don't put this in Document.Ready(). – Simon May 27 '16 at 08:06
  • @Simon thanks for this comment... I tried every combination I could find on the internet, but was trying them inside of Document.Ready() – Matt Sanders Sep 21 '16 at 22:44
8

try

 var validator = $("#form-id").data('validator');
 validator.settings.ignore = "";
Mr.LamYahoo
  • 1,536
  • 13
  • 28
7

I am not sure why do you need to show validations for fields that user cannot see or edit. But you can try this. Instead of display:none, apply visibility:hidden and height:0 to your input field.

@using (Html.BeginForm("TestModelState", "RandD", FormMethod.Post, new {id="form123" }))
{ 
    @Html.TextBoxFor(x => x.htmlText, new { style="visibility:hidden;height:0"})<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()" />
}
sanjeev
  • 1,407
  • 2
  • 18
  • 30
  • 6
    You could have other, visible fields that the user interacts with, which set the value for the hidden field. Then you might want to validate the value that has been built in the hidden field. For example, three fields for day, month and year, plus a hidden field where you set and validate the whole date. – Richard Nov 08 '18 at 21:16
  • I found that this will not work - validation is ignored for zero height and visibility:hidden – PBMe_HikeIt Oct 15 '20 at 15:23
2
var validator = $("#form-id").data("validator");    
validator.settings.ignore = ""; /* Set validator to ignore nothing. */
validator.form(); /* Validates the form, returns true if it is valid, false otherwise. */

console.log(validator.valid());
console.log(validator.errorList);