Client side validation not working for hidden field in asp.net mvc 3

三世轮回 提交于 2019-12-05 02:42:02

In the code which sets the hidden field's value, manually invoke validation for the form, like so:

$("form").validate().form();

You can wrap your hidden field with a div put somewhere but still inside the <form>. Add css to kick it to outer space.

<div style="position:absolute; top:-9999px; left:-9999px">
<input id="Rating" type="hidden" name="rating" >
</div>

Then add the following label to where you want to show the error:

<label for="rating" class="error" style="display:none">I am an an error message, please modify me.</label>

Client-side validation ignores hidden fields. You can set the "ignore" option dynamically but just to get it to work I did the following directlyl in the .js file.

For now this should do the trick.

In my aspx...

<%: Html.HiddenFor(model => model.age, new { @class="formValidator" }) %>

In jquery.validate.js

ignore: ":hidden:not('.formValidator')",

This turned out to be a very interesting issue. the default "ignore" setting is ignores hidden fields. The field was hidden in a jQuery ui plug-in. I simply added a class called "includeCheckBox" to the rendered input I wanted to validate and put the following line of code in...

var validator = $('#formMyPita').validate();
validator.settings.ignore = ':hidden:not(".includeCheckBox")';
if ($('#formMyPita').valid()) {....

I think it is because hidden inputs don't fire any of these events.

What you could do instead would be to use a <input type="text" style="display:none" /> instead of the hidden field;

@html.TextBoxFor(m => m.Rating, new {display = "display:none"})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!