17

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!

5 Answers 5

21

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.

5
  • Thank you, I will give this a try tomorrow but could you please explain how to do different validations. For example validating for an correct email address, validating that there are no more than or at least XX characters, that a form field is filled out... things like that? Commented Sep 29, 2010 at 8:54
  • Also, does this validate before the post is saved/updated? If not, how can I do that? Commented Sep 29, 2010 at 8:55
  • The examples and documentation for the jQuery Validation plugin (linked in my answer) will show you how to do all of those things. Validation happens on submit by default but you can trigger it on blur or on change for any form element for your custom fields.
    – danblaker
    Commented Sep 29, 2010 at 17:13
  • I implemented this solution and it looks very promising, one problem though, what do I put in the 'submitHandler' ? After validation with jquery.validate, Wordpress does nothing (save buttun stays in animated state). How do I pass the baby back to WP ?
    – mike23
    Commented May 11, 2011 at 9:16
  • 2
    If you're just trying to get the Publish button back to its normal state when a required field is empty (or some other validation fails), you shouldn't need to do anything with the submitHandler; just edit the validate() code to change the button when validation fails. This works: jQuery("#post").validate({ invalidHandler: function() { jQuery('#publish').removeClass('button-primary-disabled'); jQuery('#ajax-loading').css('visibility', 'hidden'); } });
    – danblaker
    Commented May 13, 2011 at 22:14
3

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)

1
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.
    – Gabriel
    Commented Jun 9, 2016 at 17:50
2

The Complete Basic Code to add jQuery Validation:

  1. Enqueue the validation script. I assume jQuery is already enqued.

    add_action('admin_enqueue_scripts',function($id){
        $validation',$validation_js_url = #your validation.js source;
        wp_register_script( 'validation',$validation_js_url,array(),'',true );
        wp_enqueue_script( 'validation' );
    });
    
  2. In the js file or script tag:

    jQuery(document).ready(function($){
        var form = $("form[name='post']");
        $(form).find("input[type='submit']").click(function(e){
            e.preventDefault();
            $(form).validate();
    
            if($(form).valid())
            {
                $("#ajax-loading").show();
                $(form).submit();
            }else{
                $("#publish").removeClass().addClass("button-primary");
                $("#ajax-loading").hide();
            }
        });
    });
    
  3. Done :)

1
2

I used this code, very helpful, justa changed:

$(form).find("input[type='submit']").click(function(e){

To:

$(form).find("#publish").click(function(e){

'Cause if you have another form inside the main form this start the script.

And:

$(form).submit();

To:

$(this).submit();

'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/

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.