问题描述
我正在使用jquery.validate插件并面临以下情况:
I'm using jquery.validate plugin and facing the following situation:
<form id="myForm" ....>
<input type="text" id="value1"/>
<!-- Here is some code rendered from the partial -->
<script type="text/javascript">
$(document).ready(function() {
var validator = $('#myForm').validate({
rules: {
value_from_partial: {
required: true
}
},
messages: {
value_from_partial: {
required: "Enter your firstname"
}
},
submitHandler: function() {
alert("submitted!");
}
});
});
</script>
<input type="text" id="value_from_partial"/>
<!-- End of code rendered from the partial -->
</form>
<script type="text/javascript">
$(document).ready(function() {
var validator = $('#myForm').validate({
rules: {
value1: {
required: true
}
},
messages: {
value1: {
required: "Enter your firstname"
}
},
submitHandler: function() {
alert("submitted!");
}
});
});
</script>
部分中添加的验证不起作用。当我从主html中删除.validate时,部分工作中的验证。看来jquery.validate不允许在同一个表单上有两个.validate调用。另一方面,我不能为验证器调用添加规则,因为我希望我的验证代码来自部分本身(实际上是一个插件)。有没有办法将我的验证逻辑与partial一起包含,并使用jqury.validate而不是手动验证。是否有其他验证框架可以允许这个?谢谢!
Validation added in the partial doesn't work. When I remove .validate from the main html, then validation in the partial works. It seems that jquery.validate doesn't allow that there are two .validate calls on the same form. On the other hand, I can not call "add" rules for validator, since I want my validation code to come from the partial itself (which is actually a plugin). Is there any way to include my validation logic together with the partial, and to use jqury.validate instead of manual validation. Is there any other validation framework that can allow this? Thanks!
推荐答案
你是不对的,你不能打电话给 validate()
两次。嗯,你可以,但选项第二次没有效果。
You're correct that you can't call validate()
twice. Well, you can, but the options have no effect the second time.
两个选项:
- 用HTML而不是JavaScript构建规则。例如,将
required
类添加到输入而不是添加所需规则。验证器支持此功能。 - 让表单的部分和主要部分构建选项 object ,然后调用
validate
在单个ready
事件中,传递此对象,而不是两次调用validate
。
- Build your rules in HTML instead of JavaScript. For example, add the
required
class to an input instead of adding a required rule. The validator supports this. - Have the "partial" and "main" parts of the form build up an options object and then call
validate
in a singleready
event, passing this object, instead of callingvalidate
twice.
这篇关于一个表单上有多个jquery验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!