Bootbox验证

时间:2013-08-25 00:41:00

标签: javascript jquery bootbox

我正在尝试使用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 个答案:

答案 0 :(得分:8)

我认为您可以在“保存”按钮回调

中返回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() {}
}]);

答案 1 :(得分:0)

如@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>