javascript - 如何使用 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>
解决方案
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.
推荐阅读
- python - 如何将以特定字符串开头的每多行转置为列?
- javascript - 将 Javascript 变量动态附加到 URL
- c++ - 使用键值对为零的 k 个桶初始化 c++14 unordered_map
- c++ - 检查是否存在 operator()
- html - Flexbox - 如何防止长文本向右移动 div?
- java - 通过 Selenium 启动浏览器时出现异常 java.lang.ClassNotFoundException: org.openqa.selenium.MutableCapabilities
- python - 为什么在添加使用 Builder.load_string() 创建的小部件后没有捕获到这个 kivy 错误?
- ios - Vscode React Native 在设备上运行
- excel - excel使用vlookup使用另一列将两个表中的两列配对
- javascript - 捆绑和缩小以及异步/等待