MVC : How to enable client side validation on hidden fields
Asked Answered
M

5

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

Matronly answered 4/7, 2014 at 10:56 Comment(11)
Client side validation works if I remove "style="display:none" from htmlText text field .Matronly
@Stilgar, you need to update your knowledge over MVC.Matronly
@Matronly 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.Napper
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 2Matronly
@Matronly for that you can use partial views as well isnt it?Revealment
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.Matronly
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?Rowenarowland
The format is ignore: []. See this and then thisTychon
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.Nonbeliever
@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.Argeliaargent
Exactly my use case @NonbelieverReckon
S
53

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.

Scandic answered 15/7, 2014 at 7:15 Comment(6)
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.Vase
I recommend setting the value to ":disabled".Cerberus
It's worth noting that this doesn't work if it's called inside the document ready (or jQuery $(function () {})shortcut) functionSpina
Well played @JamesMcCormack this comment is super duper relevant and I got stuck on that for sometime.Palmy
See also See also https://mcmap.net/q/452512/-client-side-validation-for-a-particular-hidden-field-in-asp-net-mvc for for @DJandChips idea of conditions.Intrastate
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)Fayth
W
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>
}
Watchword answered 5/3, 2015 at 7:59 Comment(3)
$.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.Ayres
Also, make sure you don't put this in Document.Ready().Endoplasm
@Endoplasm thanks for this comment... I tried every combination I could find on the internet, but was trying them inside of Document.Ready()Montgolfier
S
8

try

 var validator = $("#form-id").data('validator');
 validator.settings.ignore = "";
Southey answered 16/3, 2016 at 18:50 Comment(1)
This caused my form to not validate anything.Schoolmaster
S
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()" />
}
Spongioblast answered 4/7, 2014 at 22:18 Comment(2)
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.Rack
I found that this will not work - validation is ignored for zero height and visibility:hiddenButter
S
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);
Substitute answered 26/4, 2021 at 16:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.