Skip validation when going backwards in SmartWizar

2019-04-29 06:58发布

问题:

I am using the SmartWizard 2.0 (link) and I need to stop the validation from kicking in when the users hits the "Prev" button or in any way moves backward in the form.

Currently I am using

// Triggers whenever you change page/tab in wizard    
function leaveStep(obj) {        
    $("form").validate();
    if ($("form").valid())
        return true;

    return false;
}

I know that I can use

var currentStep = obj.attr('rel'); // get the current step number

to find the currentStep, but I need to know which way the user is navigating - so I need to know the "nextStep". Don't know if this is possible.

回答1:

When onLeaveStep is triggered could you not use the obj to determine the direction? Then you would only validate when moving to the next step?

Updated:

After looking at the source code, there is no way that I can see to figure out the direction. Patching in the ability is pretty easy however. In jquery.smartWizard-2.0.js change line 186 from

if(!options.onLeaveStep.call(this,$(curStep))){

to

if(!options.onLeaveStep.call(this,$(curStep),$(selStep))){

This now gives you access to the selected step anchor, and thus the selected step index. To determine the direction in your onLeaveStep handler simple do the following:

// Triggers whenever you change page/tab in wizard    
function leaveStep(from, to) {
    var fromStepIdx = from.attr( "rel" );
    var toStepIdx = to.attr( "rel" );

    if ( toStepIdx < fromStepIdx )
    {
        return true;
    }

    $("form").validate();
    if ($("form").valid())
        return true;

    return false;
}


回答2:

In case anyone happens upon this later (as somebody just did, and emailed me due to their confusion): There is a newer version available on github.

Among other things, it provides your callback with "fromStep" and "toStep" values in an object.

For example:

$('#wizard').smartWizard({
    onLeaveStep:function(obj, context) {
        if (context.fromStep > context.toStep) {
            // Going backward
        } else {
            // Going forward
        }
    }
});


回答3:

Mark's answer is correct, you can use the context.fromText and context.toStep to detect direction, but I found that without return true;, smartWizard may not validate the transition (going from step 1 to 2 is allowed, not step 1 to 3, etc.) and allow it to occur.

$('#wizard').smartWizard({
onLeaveStep:function(obj, context) {
    if (context.fromStep > context.toStep) {
        // Going backward
    } else {
        // Going forward
    }
    return true;
}
});