How to trap “Publish” button to check for meta box validation?

I’m trying to do some form validation on my custom meta box, and I remember somewhere reading about some javascript function to disable/enable the Publish button – except I can’t find it.

How do I either

Read More

a) enable/disable the publish button or,

b) when Publish is clicked, trap it and prevent the update and alert the user, but in such a way that it can be updated later

I’ve tried just a simple click handler with e.preventDefault() and e.stopPropagation however the swily icon comes up and the button stays disabled because it never finishes

Thanks

Related posts

Leave a Reply

2 comments

  1. Rather than trying to interfere with the button operation and doing validation in jQuery or javascript, I find it easier to hook the save_post action and do my validation in php (checking if certain post_meta exist or are correct), then if things don’t check out, you can set the post status back to “pending”, which in effect overrides the Publish button. The page simply loads back up (having been saved), but they have to correct their errors before “publishing” can be done.

  2. I’m using jQuery Tools Validator

    $("#publish").click(function(event){
    
        //validating
        var inputs = $(".TTWForm-container :input").validator();
    
        //check if not valid stop loading ajax icons
        if( ! inputs.data("validator").checkValidity()){               
            event.stopImmediatePropagation();              
        }
    
    }
    

    This code fires once the publish button is clicked, then checks if the form is valid or not. If it is not, it stops all events propagation, which shows the Ajax loading icons and so otherwise it works without a problem.