Validating Custom Meta Box Values & Required Fields

The easiest way is to add Javascript validation via the jQuery Validate plugin. Here’s the most basic walkthrough:

Near your add_meta_box call, enqueue the jQuery Validate plugin as well as a JS file for your simple script:

add_action('admin_enqueue_scripts', 'add_my_js');   
function add_my_js(){    
  wp_enqueue_script('my_validate', 'path/to/jquery.validate.min.js', array('jquery'));
  wp_enqueue_script('my_script_js', 'path/to/my_script.js');
}

Then in my_script.js include the following:

jQuery().ready(function() {
    jQuery("#post").validate();
});

This will enable validation on the post form. Then in the add_meta_box callback where you define the custom fields, you’d add a “required” class for each field you wish to validate, like so:

<input type="text" name="my_custom_text_field" class="required"/>

All fields with “required” in their class will be validated when the post is saved/published/updated. All of the other validation options (rules, error styling, etc) can be set in the document.ready function in my_script.js; check the jQuery Validate docs for all the options.

Leave a Comment