简体   繁体   English

在 ASP.NET MVC 表单上禁用不显眼的验证

[英]Disable unobtrusive validation on an ASP.NET MVC form

I have two forms on a page.我在一个页面上有两个表格。 I want the first form to use unobtrusive validation, as it's since automatically generated by ASP.NET MVC Framework.我希望第一个表单使用不显眼的验证,因为它是由 ASP.NET MVC 框架自动生成的。 There is a second form, however, which I wrote manually, that should not use unobtrusive validation.还有第二个形式,但是,这是我写的手动,应该使用不引人注目的验证。

Here's some code:这是一些代码:

@using (Html.BeginForm("Add", "Contacts", FormMethod.Post, new { id = "AddForm" }))
{
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Datos Contacto</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.ContactDepartmentID)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.ContactDepartmentID, (List<SelectListItem>)ViewBag.ContactDepartments)
            @Html.ValidationMessageFor(model => model.ContactDepartmentID)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Sex)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.Sex, (List<SelectListItem>)ViewBag.Sexs)
            @Html.ValidationMessageFor(model => model.Sex)
        </div>
    </fieldset>
    <br />
    @Html.HiddenFor(model => model.SerializedEmails, new { data_bind = "value: ko.toJSON($root.emails())" })
    @Html.HiddenFor(model => model.SerializedPhones, new { data_bind = "value: ko.toJSON($root.phones())" })
}
<form id="phoneForm" >
<fieldset>
    <legend>Teléfonos</legend>
    <table class="table">
        <tbody data-bind="foreach: phones">
            <tr>
                <th>
                    Celular?
                </th>
                <th>
                    Phone
                </th>
                <th>
                    Extension
                </th>
                <th>
                </th>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" data-bind="checked: isMobile" />
                </td>
                <td>
                    <input class="phone" data-bind='value: phone'/>
                </td>
                <td>
                    <input type="text" class="extension" data-bind='value: phoneExtension, enable: !isMobile() ' />
                </td>
                <td>
                    <a href='#' data-bind='click: $root.removePhone'>Delete</a>
                </td>
            </tr>
        </tbody>
    </table>
    <a href='#' data-bind='click: $root.addPhone'>Agregar teléfono</a>
</fieldset>
</form>
<p>
    <button onclick="Submit();" type="button" class="btn btn-primary" data-bind='enable: phones().length > 0 || emails().length > 0'>
        Create</button>
</p>

JS: JS:

function Submit()
{      
  var valid = $('#AddForm').valid();     
  var valid2 =  $('#phoneForm').valid();     
}

jQuery.validator.addClassRules("phone", {
  required: true
});

As a side note: When I remove the unobtrusive validation from the page, the second form validates, but the first does not.作为旁注:当我从页面中删除不显眼的验证时,第二个表单会验证,但第一个不会。 If I use unobtrusive validation the first form validates, but the second form does not.如果我使用不显眼的验证,第一个表单会验证,但第二个表单不会。

I know I can do the whole validation on the client side—and, if that's the only way, I will do it.我知道我可以在客户端完成整个验证——如果这是唯一的方法,我会这样做。 I was thinking about a way to continue using unobtrusive validation, but allowing it to be conditionally disabled using eg custom attributes.我正在考虑一种继续使用非侵入式验证的方法,但允许使用例如自定义属性有条件地禁用它。

You can disable the unobtrusive validation from within the razor code via this Html Helper property:您可以通过此 Html Helper 属性从 razor 代码中禁用不显眼的验证:

HtmlHelper.ClientValidationEnabled = false;

That way you can have unobtrusive validation on and off for different forms according to this setting in their particular view/partial view.这样,您可以根据特定视图/部分视图中的此设置对不同表单进行不显眼的验证。

You can mark the elements or find it all the input of the second form and remove the rules, this sample is for remove all rules of some controls in the form, this cause according with the user selected some options, the values required will be others.可以标记元素或者找到第二个form所有input并删除规则,本示例是删除表单中某些控件的所有规则,这个原因根据用户选择的一些选项,需要的值会是其他的. for this reason i store the rules to restore it later.出于这个原因,我存储规则以便稍后恢复。

///Remove rules
$("input.rO,textarea.rO").each(function () {
   try
   {
      var rule = $(this).rules();
      if (rule) {
         $(this).data("rule", rule);
         $(this).rules("remove");
     }
  }
  catch(err){}
 });
 ///Restore rules
 $("input.rO.om" + v + ",textarea.rO.om"+v).each(function () {
      try
      {
        var rule = $(this).data("rule");
        if (rule)
           $(this).rules("add", rule);
      }
      catch(err){}
    });

If you remove unobtrusive-validation , then you are simply using the jQuery Validate plugin by itself.如果您删除unobtrusive-validation ,那么您只是在单独使用 jQuery Validate 插件。

If that's the case, then you must follow the documentation for the plugin.如果是这种情况,那么您必须遵循插件的文档。 The .valid() method can only be used after the plugin is first initialized via the .validate() method .所述.valid()之后的插件经由第一初始化只能用方法.validate()方法 Also see: http://jqueryvalidation.org另见: http : //jqueryvalidation.org

However, there is no need to wrap anything inside of a submit function or handler.但是,不需要在submit函数或处理程序中包装任何东西。 The plugin automatically captures the submit event if the plugin is properly initialized.如果插件正确初始化,插件会自动捕获提交事件。

$(document).ready(function() {

    $('#myform').validate({
        // rules and options
    });

    jQuery.validator.addClassRules("phone", {
         required: true
    });

});

Simple DEMO: http://jsfiddle.net/DW4qE/简单演示: http : //jsfiddle.net/DW4qE/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM