如何使用jQuery validate插件在非表单元素上验证输入 [英] How to validate input, in non-form element, on keyup with jQuery validate plugin

查看:240
本文介绍了如何使用jQuery validate插件在非表单元素上验证输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在ASPX中构建的网站.不幸的是,由于这个事实,我实际上不能使用<form>标记来包装我的输入,据我所见, jQuery Validation Plugin 仅支持验证<form>中的输入.是否有任何方法可以使用指定的规则在keyup上验证这些输入,而不必将它们包装在<form>标记中?

I have a site that is being built in ASPX. Unfortunately, because of this fact, I cannot actually use the <form> tag to wrap my inputs, and as far as I can see, jQuery Validation Plugin only supports validating inputs within a <form>. Is there any way to validate these inputs, using the specified rules, on keyup without having them wrapped in a <form> tag?

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

推荐答案

您不能具有嵌套表单,该表单是无效的HTML,并且必须将.validate()附加到form容器.没有解决方法.

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

您还使用.validate()都错了.由于这是插件的主要初始化方法,因此将其包装在keyup处理程序中是不正确的.另外,该插件已经使用keyup事件来触发验证.

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.

不,您不能将表单输入元素放在div中,然后将div附加到.validate().它将被忽略.您只能定位附加到.validate()form元素.

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

此外,由于使用的是ASP,因此可以利用其内置的Unobtrusive Validation插件,该插件会根据您的数据属性自动构造并调用.validate()方法.请记住,如果遵循此路线,您将无法自行呼叫.validate().该插件仅允许一个调用,并且一旦初始化,对.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.

这篇关于如何使用jQuery validate插件在非表单元素上验证输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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