Search code examples
javascriptjquerybootbox

Bootbox validation


I am trying to create a modal using Bootbox. I have the modal popup and ask you to fill in some data. I am then trying to do validation so when they click on save, it checks to just make sure the fields are filled in.

How can I prevent the modal from closing when clicking save if validation fails?

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

Solution

  • I think you can just return false in your "Save" button callback

    like this:

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