0

我正在为我的一个项目使用 jQuery SmartWizard。我通过似乎正在工作的 jQuery Validation 插件进行了验证。问题是,如果当前步骤的验证失败,我希望 SmartWizard 阻止用户导航到下一步。

下面的代码似乎可以工作,因为我可以看到Form on step X is invalid控制台日志条目,但是return false即使验证明显失败,下面的应该会阻止用户导航到下一步的代码似乎被忽略了。

我也尝试将函数绑定到按钮的click事件sw-btn-next,这是单击以继续下一步的按钮,但这似乎也不起作用。

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.')
});
4

1 回答 1

1

经过大量的反复试验,我终于通过将验证检查从 SmartWizard 的stepContent事件移至事件来解决了这个问题leaveStep。请注意,经常引用的$('.sw-btn-next').click(function()也不起作用,它必须是leaveStep.

// ###################################
// # 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
    justified: true, // Nav menu justification. true/false
    darkMode: false, // Enable/disable Dark Mode if the theme supports. true/false
    autoAdjustHeight: true, // Automatically adjust content height
    cycleSteps: false, // Allows to cycle the navigation of steps
    backButtonSupport: true, // Enable the back button support
    enableURLhash: false, // Enable selection of the step based on url hash
    // onFinish: onFinishCallback,
    // onCancel: onCancelCallback,
    transition: {
        animation: 'fade', // Effect on navigation, none/fade/slide-horizontal/slide-vertical/slide-swing
        speed: '400', // Transion animation speed
        easing: '' // Transition animation easing. Not supported without a jQuery easing plugin
    },
    toolbarSettings: {
        toolbarPosition: 'bottom', // none, top, bottom, both
        toolbarButtonPosition: 'center', // left, right, center
        showNextButton: true, // show/hide a Next button
        showPreviousButton: true, // show/hide a Previous button
        toolbarExtraButtons: [ // Extra buttons to show on toolbar, array of jQuery input/buttons elements
            $('<button id="newUserSubmit" class="btn btn-sm btn-primary-bordered" disabled><i class="fa fa-check mr-15"></i> Submit</button>')
        ]
    },
    anchorSettings: {
        anchorClickable: false, // Enable/Disable anchor navigation
        enableAllAnchors: false, // Activates all anchors clickable all times
        markDoneStep: false, // Add done state on navigation
        markAllPreviousStepsAsDone: true, // When a step selected by url hash, all previous steps are marked done
        removeDoneStepOnNavigateBack: false, // While navigate back done step after active step will be cleared
        enableAnchorOnDoneStep: true // Enable/Disable the done steps navigation
    },
    keyboardSettings: {
        keyNavigation: false, // Enable/Disable keyboard navigation(left and right keys are used if enabled)
        keyLeft: [37], // Left key code
        keyRight: [39] // Right key code
    },
    lang: { // Language variables for button
        next: 'Next >',
        previous: '< Previous'
    },
    // disabledSteps: [],                       // Array Steps disabled
    // errorSteps: [],                          // Highlight step with errors
    // hiddenSteps: []                          // Hidden steps

    // when changing steps...
}).on("stepContent", function(e, anchorObject, stepIndex, stepDirection) {
    // on step 1, focus on First Name input field
    if (stepIndex == 1) {
        $("#first_name").focus();
    }

    // check if current step is stepIndex 4 and enable submit button
    if (stepIndex == 4) {
        // enable form submit button on last step
        $('#newUserSubmit').prop('disabled', false);
        console.log('StepIndex is 4, enabling submit button');
    } else {
        // disable form submit button on all other steps
        $('#newUserSubmit').prop('disabled', true);
        console.log('StepIndex is not 4, disabling submit button');
    }
});

// Initialize the leaveStep event
$("#smartwizard").on("leaveStep", function(e, anchorObject, stepIndex, nextStepIndex, stepDirection) {
    // navigate to next step
    console.log('Navigated to stepIndex ' + stepIndex + ' moving in stepDirection ' + stepDirection);

    // check if current form step is valid
    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;
        }
    }
});

form上面的代码工作通过在用户导航离开当前步骤时调用整个验证,为每个步骤提供了一个有效的 SmartWizard 分步向导和 jQuery 验证。此外,脚本会在向导中放置一个额外的Submit按钮,除非用户已到达向导的最后一步,否则该按钮会自动禁用。

这个特定用例的文档非常少,我希望这可以帮助其他遇到 SmartWizard 和 jQuery 验证问题的人。

于 2021-11-19T02:55:34.480 回答