使用jQuery Validate插件validation表单的子集
我的HTML表单有许多div,它们是向导的步骤。 单击“下一步”按钮后,我想validation活动div。 我正在使用jQuery.Validate.js插件。
每个div都有一个ID,所以我想要一种方式来说:
wizardForm.validate().element('#first-step :input')
但这只能validation第一个输入,而不是所有输入。 如何validationdiv中的所有输入?
根据jAndy的建议,我创建了这个辅助函数:
jQuery.validator.prototype.subset = function(container) { var ok = true; var self = this; $(container).find(':input').each(function() { if (!self.element($(this))) ok = false; }); return ok; }
用法:
if (wizardForm.validate().subset('#first-step')) { // go to next step }
我尝试了这个解决方案,它对我不起作用。 所以这是我如何使用jquery.validation插件实现相同的行为。
validation者:
var form = $('#form'); // init validator obj and set the rules form.validate({ errorElement: 'span', //default input error message container errorClass: 'help-inline', // default input error message class focusInvalid: false, // do not focus the last invalid input ignore: "", rules: { // the rules, as usual }, highlight: function (element) { // hightlight error inputs $(element).closest('.control-group').addClass('error'); // set error class to the control group }, unhighlight: function (element) { // revert the change dony by hightlight $(element) .closest('.control-group').removeClass('error'); // set error class to the control group } });
使用bootstrap表单向导 。
这就是我validation每个步骤的方法:
$('#step :input').valid()
奇迹般有效。
如果查看validate()
函数的选项,其中一个选项是ignore
,默认情况下会阻止validation程序尝试validation与CSS伪类匹配的任何字段:hidden
。 我将它与FuelUX向导结合使用,并且能够阻止向导进入下一步,具体如下:
$( '#wizard' ).wizard().on( 'change', function( event, info ) { if ( ! $( '#wizard_form' ).valid() ) event.preventDefault(); });