jQuery 在 <form> 之外的提交按钮中使用 "formnovalidate" 进行验证

jQuery Validation with "formnovalidate" in submit button outside the <form>

我有一个使用 jQuery 验证插件的编辑表单。它是 ASP.NET 核心项目的一部分,也使用 ASP.NET 的 Unobtrusive Validation 插件。该表单有两个提交按钮,post发送到服务器端的不同处理程序:

“提交更改”工作正常,但我希望“删除”按钮跳过任何客户端验证。目前,如果缺少任何必填字段(或任何其他验证条件未通过),它不会 post 表单。

我试过“删除”按钮上的 HTML5 formnovalidate 属性,但没有成功。 jQuery 验证插件中是否有等效功能?如果不是,您将如何仅针对特定提交按钮绕过验证?

编辑:

“删除”按钮实际上位于 <form> 标记之外,但通过 form 属性按 ID 引用表单:

<form id="my-form">
  <!-- form fields and submit button here -->
</form>
<button type="submit" form="my-form" noformvalidate asp-page-handler="Delete">
  Delete entry
</button>

我发现在 <form> 内移动“删除”按钮时,noformvalidate 属性按预期工作。我真的很想将此按钮保留在 <form> 标记之外(由于页面的布局),但如果没有其他方法,我也许可以解决它。

关于如何使其在放置在表单之外时跳过验证的任何想法?

你的问题好像总结了in this issue:

Typical save vs submit button where save does not validate and submit does. Save button is declared with the formnovalidate attrribute. Only thing is that these buttons are outside of the form itself.

看,该插件希望提交按钮位于您的表单内。它实际上仍然处理 'preventing' 标志 - cancel class 和 formnovalidate 属性 - 在 click 处理程序中从按钮传播到顶部表格 (source):

// "this" is jQuery-wrapped HTMLFormElement with validator attaching
this.on( "click.validate", ":submit", function( event ) {
  // Track the used submit button to properly handle scripted
  // submits later.
  validator.submitButton = event.currentTarget;

  // Allow suppressing validation by adding a cancel class to the submit button
  if ( $( this ).hasClass( "cancel" ) ) {
    validator.cancelSubmit = true;
  }

  // Allow suppressing validation by adding the html5 formnovalidate attribute to the submit button
  if ( $( this ).attr( "formnovalidate" ) !== undefined ) {
    validator.cancelSubmit = true;
  }
} );

... 如果按钮在 DOM 层次结构之外,这显然不起作用,就像你的情况一样。仅 submit.validate 处理程序被触发,但它期望检查 validator.cancelSubmit 标志(如果它是真实的,则将其设置为 false)。

我想到的一个想法是将您自己的点击处理程序放在 Delete 按钮上,这将覆盖该标志。 Validator 实例可以通过 $.data 形式访问,通常使用 jQuery 插件:

const validator = $.data(form, 'validator');