使用JQuery验证来验证字段,而无需提交任何内容? [英] Validate fields using JQuery validation without any submit?
问题描述
我有一个HTML5 Web应用程序,其中包含许多用户输入的字段,并且在将它们发送到服务器之前,我想对javascript中的这些字段进行一些客户端验证.容易吧?只需使用JQuery验证插件--- http://jqueryvalidation.org/
但是有一个陷阱.我的网络应用程序没有表格. HTML中没有任何提交.而是在每个用户可更改的元素上都有一个JQuery更改处理程序,并且当用户更改这些元素之一的值时,将进行AJAX调用. (这种非标准的用户交互体系结构对此应用程序很有意义.)
我想在AJAX调用之前验证字段,并使用JQuery验证插件来执行此操作.但是我不知道怎么做.
是否可以使用JQuery验证插件而无需在任何地方提交?我该怎么做?还是另一种方法更好?
首先,最重要的是,您 必须 在<form></form>
标记内,以使jQuery Validate插件运行.但是,不需要提交按钮.
其次,您可以使用 http://jsfiddle.net/URQGG/ >
I have a HTML5 web application with numerous user-entered fields, and I would like to do some client-side validation on those fields in javascript before sending them to the server. Easy right? Just use JQuery validation plugin --- http://jqueryvalidation.org/
But there's a catch. My web app has no forms. There is no submit anywhere in the HTML. Instead there's a JQuery change handler on every user-changeable element, and when the user changes the value of one of those element, an AJAX call is made. (This nonstandard user interaction architecture makes sense for this application.)
I would like to validate the field before the AJAX call, and use the JQuery validation plugin to do that. But I can't figure out how.
Is it possible to use the JQuery validation plugin without a submit anywhere? How would I do this? Or is another approach better?
Firstly, and most importantly, you must wrap your input elements inside <form></form>
tags for the jQuery Validate plugin to operate. However, a submit button is not required.
Secondly, you can programatically trigger the validity test of any or all elements without a submit button by using the .valid()
method.
$(document).ready(function() {
$('#myform').validate({ // initialize the plugin on your form.
// rules, options, and/or callback functions
});
// trigger validity test of any element using the .valid() method.
$('#myelement').valid();
// trigger validity test of the entire form using the .valid() method.
$('#myform').valid();
// the .valid() method also returns a boolean...
if ($('#myform').valid()) {
// something to do if form is valid
}
});
DEMO: http://jsfiddle.net/URQGG/
这篇关于使用JQuery验证来验证字段,而无需提交任何内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!