首页 > 解决方案 > 如何使用 jQuery 验证插件在 keyup 上验证非表单元素中的输入

问题描述

我有一个正在用 ASPX 构建的网站。不幸的是,由于这个事实,我实际上不能使用<form>标签来包装我的输入,而且据我所知,jQuery Validation Plugin仅支持在<form>. 有没有办法使用指定的规则验证这些输入,keyup而不用将它们包装在<form>标签中?

$(function() {
  $('.form-container').validate({
    rules: {
      useremail: {
        required: true,
        email: true
      },
      userstate: {
        required: true,
        maxlength: 2
      }
    },
    messages: {
      useremail: 'Please enter a valid email',
      userstate: 'Please enter your state',
    }
  });
  
  $('.form-container input').on('keyup', function() {
    $(this).validate();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.18.0/jquery.validate.min.js"></script>

<div class="form-container">
  <input type="text" name="useremail" placeholder="Email" />
  <input type="text" name="userstate" placeholder="State" maxlength="2" />
</div>

标签: javascriptjqueryasp.netjquery-validate

解决方案


You cannot have nested forms, which is invalid HTML, and you must attach .validate() to a form container. There are no workarounds.

You're also using .validate() all wrong. Since this is the primary initialization method of the plugin, wrapping it within a keyup handler is not correct. Plus the plugin already uses the keyup event to trigger validation.

And no, you cannot put form input elements within a div and then target that div attached to .validate(). It will be ignored. You can only target form elements attached to .validate().

Furthermore, since you're using ASP, you can leverage its built-in Unobtrusive Validation plugin, which automatically constructs and calls the .validate() method based upon your data attributes. Just remember that if you follow this route, you cannot call .validate() yourself. The plugin only allows one call, and once initialized, all subsequent calls to .validate() are ignored.


推荐阅读