【发布时间】:2023-03-18 21:18:02
【问题描述】:
我正在为我的一个项目使用 jQuery SmartWizard。我通过似乎正在工作的 jQuery Validation 插件进行了验证。问题是,如果当前步骤的验证失败,我希望 SmartWizard 阻止用户导航到下一步。
下面的代码似乎可以工作,因为我可以看到Form on step X is invalid 控制台日志条目,但下面的return false 应该会阻止用户导航到下一步,即使验证明显失败,它似乎也被忽略了.
我也尝试将函数绑定到sw-btn-next 按钮的click 事件,该按钮是单击以继续下一步的按钮,但这似乎也不起作用。
jQuery 3.2.1 // Bootstrap 3.3.7 // SmartWizard 5.1.1(最新) // jQuery Validation 1.19.3(最新)
jQuery 验证
// set validation rules for entire form
$('#addNewUser').validate({
debug: true,
errorElement: 'span',
errorClass: 'form-text form-error text-red',
focusInvalid: false,
rules: {
'first_name': {
required: true,
minlength: 3
},
'last_name': {
required: true,
minlength: 3,
},
'password': {
required: true,
minlength: 5,
maxlength: 25
},
'password_repeat': {
required: true,
minlength: 5,
maxlength: 25,
equalTo: '#password'
}
},
messages: {
'first_name': 'Please enter a valid first name'
}
});
智能向导
// ###################################
// # jQuery SmartWizard plugin
// ###################################
$('#smartwizard').smartWizard({
selected: 0, // Initial selected step, 0 = first step
theme: 'default' // theme for the wizard, related css need to include for other than default theme
// when changing steps...
}).on("stepContent", function(e, anchorObject, stepIndex, stepDirection) {
// check if current step is Step 5 and enable submit button
$('#newUserSubmit').prop('disabled', stepIndex !== 4);
console.log('Navigated to stepIndex ' + stepIndex + ' moving in stepDirection ' + stepDirection);
// check form validation
var elmForm = $('#form-step-' + stepIndex);
if (stepDirection == 'forward' && elmForm) {
if ($('#addNewUser').valid()) {
console.log('Form on Step ' + stepIndex + ' is valid');
return true;
} else {
console.log('Form on Step ' + stepIndex + ' is invalid');
return false;
}
}
});
// when clicking NEXT button...
$('.sw-btn-next').click(function() {
console.log('Next button clicked.')
});
【问题讨论】:
-
不知道为什么它不起作用。默认情况下,Validate 插件会忽略隐藏的部分,仅验证显示的步骤。请参阅:stackoverflow.com/q/68561398/594235 否则,我会将其分解为单独的形式。见:stackoverflow.com/q/17748545/594235
-
我刚才确实尝试过,每一步将一个长表单分解为一个表单,但
.validate似乎不适用于多个字段。链接的帖子来自 8 多年前,很可能不再支持这种调用验证的方式。 -
该插件的核心今天与 8 年前一样。
标签: javascript jquery twitter-bootstrap-3 jquery-validate smart-wizard