Bootbox验证

4

我正在尝试使用Bootbox创建一个模态框。我已经有了弹出的模态框,并要求您填写一些数据。然后,我尝试进行验证,以便在单击保存时,它仅检查字段是否已填写。

如果验证失败,我该如何防止单击保存时关闭模态框?


bootbox.dialog(header + content, [{
    "label": "Save",
    "class": "btn-primary",
    "callback": function() {

        title = $("#title").val();
        description = $("#description").val();
        icon = $("#icon").val();
        href = $("#link").val();
        newWindow = $("#newWindow").val();
        type = $("#type").val();
        group = $("#group").val();

            if (!title){ $("#titleDiv").attr('class', 'control-group error'); } else {
                addMenu(title, description, icon, href, newWindow, type, group);
            }
    }
}, {
    "label": "Cancel",
    "class": "btn",
    "callback": function() {}
}]);
2个回答

13

我认为您可以在“保存”按钮回调函数中只返回false,就像这样:

bootbox.dialog(header + content, [{
    "label": "Save",
    "class": "btn-primary",
    "callback": function() {

        title = $("#title").val();
        description = $("#description").val();
        icon = $("#icon").val();
        href = $("#link").val();
        newWindow = $("#newWindow").val();
        type = $("#type").val();
        group = $("#group").val();

            if (!title){ 
                $("#titleDiv").attr('class', 'control-group error'); 
                return false; 
            } else {
                addMenu(title, description, icon, href, newWindow, type, group);
            }
    }
}, {
    "label": "Cancel",
    "class": "btn",
    "callback": function() {}
}]);

但是,如果回调函数返回false,则无法通过单击“取消”按钮关闭模型。请提供您的想法。 - Ajeet Malviya

1

正如@AjeetMalviya所评论的那样,@bruchowski发布的解决方案在使用return false;时无法关闭Bootbox。当单击取消按钮时,回调返回null;当单击确定按钮时,回调返回空字符串。

<script>
    var bb = bootbox.prompt({
        title: 'Input Required',
        onEscape: true,
        buttons: {
            confirm: {
                label: '<svg><use xlink:href="/icons.svg#check" /></svg> OK'
            },
            cancel: {
                label: '<svg><use xlink:href="/icons.svg#x" /></svg> Cancel',
                className: 'btn-secondary'
            }
        },
        inputType: 'password',
        callback: function (result) {
            //result is null when Cancel is clicked
            //empty when OK is clicked
            if (result === null) {
                return;
            } else if (result === '') {
                bb.find('.bootbox-input-password').addClass('input-validation-error');
                return false;
            }

            console.log(result);
        }
    });

    bb.init(function () {
        //do stuff with the bootbox on startup here
    });
</script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接