Something which I have never seen covered is the best way to validate that specific form fields are filled out correctly for custom post type meta boxes.
I am looking to get expert opinions on how best to validate custom fields for any metaboxes that one might create. My interest are to:
- ensure field validation takes place before the post is published/updated
- utilizing a class/code which does not conflict with other wordpress javascript
- allows you to define specific fields as required while others could be optional
- validate fields based on customizable rules including regex for things like email format
- control the visual display of any errors/notices
Thanks in advance!
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:
Then in my_script.js include the following:
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:
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.
I found this approach to solve the problem of validate metabox fields using PHP code
https://tommcfarlin.com/post-meta-data-error-messages/
Hope this help you (works for me in a similar scenario)
The Complete Basic Code to add jQuery Validation:
Enqueue the validation script. I assume jQuery is already enqued.
In the js file or script tag:
Done 🙂
I used this code, very helpful, justa changed:
To:
‘Cause if you have another form inside the main form this start the script.
And:
To:
‘Cause the first line only save the post as draft and you can’t publish it no more.
Written everything here: http://allgraphics.it/blog/2012/10/jquery-validation-sui-campi-di-input-postcustom-post-di-wordpress/
If you want to be able to validate server side the easiest option is to use Advanced Custom Fields to define your custom field layouts, and then the Validated Field add-on to set your validation per field in the WordPress Admin.