MVC:如何在隐藏字段上启用客户端验证 [英] MVC : How to enable client side validation on hidden fields

查看:129
本文介绍了MVC:如何在隐藏字段上启用客户端验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@脚本

 <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>

@查看

@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()" />
}

我尝试过的事情

  1. 在validate.js中将 ignore::hidden" 替换为 ignore:"
  2. var validateMeta = $('#form123').validate(); validateMeta.settings.ignore =";

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

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

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

推荐答案

我遇到了同样的问题.页面上的一个隐藏字段正在存储用户ID,该用户ID是从自动填充文本框中选择的.此ID进行了验证,以确保发回一个非零ID.我们希望将此验证包含在客户端中.

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.

默认情况下,jQuery validate会忽略隐藏字段,宽度和高度为零的元素,具有CSS display:none的元素以及任何具有不可见父元素的元素(使用相同条件).

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).

不过,可以通过添加以下脚本来覆盖忽略设置(我在调用$ .validator.addMethod()之前将其添加到自定义验证器脚本中):

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 });

注意:如果该代码在document ready或jQuery $(function () {})方法中运行,则将无法运行.

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

这篇关于MVC:如何在隐藏字段上启用客户端验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆