jQuery Validate:如何验证非表单元素?
我有一张附有地图的表格。单击地图会将隐藏的输入添加到表单中的 div 中。
我想要一个验证规则来检查该 div 是否有任何隐藏元素。到目前为止,我只能使用一个虚拟元素来做到这一点,在发布表单之前我必须手动删除该元素:
<form action="..." method="post" id="signup">
<!-- ... -->
<div id="zones_selected"><input type="hidden" name="dummy"></div>
<!-- ... -->
</form>
$.validator.methods.zones = function (value, element, param) { return ($zone_holder.find('input[name!=dummy]').length > 0); };
$('#signup').validate({
rules: {
//...
'dummy': 'zones'
},
//...
submitHandler: function(form) { $(form).find('input[name=dummy]').remove(); form.submit(); }
});
但是,这些对于错误放置还有很多需要改进的地方,因为我的自定义验证器方法似乎从来没有触发 unhighlight
函数,我觉得自己很脏,因为仅仅为了表单验证而输入了输入(不是很不引人注目)。
我想要的是没有额外的 submitHandler
和一个规则来检查 div 中是否存在隐藏输入,该 div 会具有 unhighlight
触发器(这样,如果用户确实单击地图——它创建了一个新的隐藏输入——我显示的告诉他们这样做的消息将会消失)。
实现这一目标的最佳方法是什么?
I have a form that has an attached map. Clicking on the map adds hidden inputs to a div in the form.
I want a validation rule to check whether or not that div has any hidden elements. So far, I've only been able to do this with a dummy element that I have to manually remove before posting the form:
<form action="..." method="post" id="signup">
<!-- ... -->
<div id="zones_selected"><input type="hidden" name="dummy"></div>
<!-- ... -->
</form>
$.validator.methods.zones = function (value, element, param) { return ($zone_holder.find('input[name!=dummy]').length > 0); };
$('#signup').validate({
rules: {
//...
'dummy': 'zones'
},
//...
submitHandler: function(form) { $(form).find('input[name=dummy]').remove(); form.submit(); }
});
However, these leaves much to be desired for error placement, as my custom validator method doesn't seem to ever trigger the unhighlight
function, and I feel dirty for having put in an input solely for form validation (not very unobtrusive).
What I would like is no extra submitHandler
and a rule to check the presence of hidden inputs in a div that would have an unhighlight
trigger (such that if a user does click on the map--which creates a new hidden input--the message I display telling them to do so will disappear).
What's the best way to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我过去曾尝试这样做。我不相信有一种方法可以在不对 jquery.validator 代码库进行一些修改的情况下做到这一点。
当查看 JQuery.Validator.js 时,查看 ln 423 上的“elements”函数,您会看到类似这样的内容:
Filter(":input") 会让您感到悲伤。
I've tried to do this in the past. I don't believe there is a way to do it without doing some modifications to the jquery.validator code base.
When looking at JQuery.Validator.js, check out 'elements' function on ln 423 you'll see something like this
The filter(":input") is what will give you grief.