Plugin code to add JS validation of "required" fields

Justin Sternberg edited this page Aug 1, 2017 · 5 revisions

Table of Contents generated with DocToc


This sample plugin code adds JS validation to any field that has the 'data-validation' attribute set to 'required':

	'attributes' => array(
		'data-validation' => 'required',


When the Publish/update button is pressed, the code will look for any "required" fields that have not been filled in. If there is one or more such fields, the code will:

  • Cancel the Publish/update process
  • Pop-up an alert message saying "The following fields are required and highlighted below" with a list of the fields after it
  • Highlight all required fields that need to be filled in
  • Center the first required field in the center of the browser so that the user sees it and can fill the field in

This sample code has not been tested with all field types available in CMB2.

Field types known to work with the code so far are:

  • text
  • file
  • file_list

Note that the code will enable JS validation on all metaboxes on your site. It is not possible with this code to select particular metaboxes or fields for validation.


Code provided by Justin Sternberg

Plugin code

Plugin code can be found in the CMB2 Snippet Library.


  1. Home

  2. Installation
    Installation instructions for various environments

  3. Basic Usage
    Get up and running

  4. Advanced Usage
    Not for the faint of heart

  5. Field Types
    Breakdown of field types

  6. Examples
    Examples for registering fields

  7. Field Parameters
    Breakdown of common field parameters

  8. Display Options
    Limit display of boxes

  9. Box Properties
    Breakdown of box properties

  10. Troubleshooting
    Common issues & how to deal with them

  11. Notable Changes in CMB2 (from original CMB)
    CMB2 — a complete re-write

  12. Tips & Tricks
    10x your CMB2 skills

  13. REST API
    CMB2 data through WordPress REST API

  14. Javascript API
    Work with CMB2 JS events & hooks

Advanced tutorials:

External Resources:

Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.