8

I've found very little on this site or in Google searches for examples of validating metabox custom fields.

If anyone wants to give examples, here are some cases that would be useful

1) Date entered as 05/02/2011 is valid date format
2) Number entered in text box is numeric and between 100 and 500
3) Text in text box is > 25 chars long

My question is not so much the code to validate the fields but where to put the validation code? Use Javascript or PHP? If it hooks on save-post, techniques for dealing with failed validation - Update the post? Don't update the post? - how do you stop it from updating? Best way to notify the user of the problems.

All suggestions are appreciated. Sample code is more helpful than just a description of a technique. ( This would be a very good topic for someone to write an article on. ) Thank you

3

3 Answers 3

2

Straight from the WP Codex @ http://codex.wordpress.org/Function_Reference/add_meta_box, you call the save_post hook and specify the function that will be run to validate/save your data:

/* Do something with the data entered */
add_action('save_post', 'myplugin_save_postdata');

Then you define that function, which will automatically be passed the post id. Additionally, you can access the $_POST array to get the values in your metaboxes:

/* When the post is saved, saves our custom data */
function myplugin_save_postdata( $post_id ) {
  // verify if this is an auto save routine. 
  // If it is our form has not been submitted, so we dont want to do anything
  if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
      return $post_id;

  // verify this came from the our screen and with proper authorization,
  // because save_post can be triggered at other times

  if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename(__FILE__) ) )
      return $post_id;


  // Check permissions
  if ( 'page' == $_POST['post_type'] ) 
  {
    if ( !current_user_can( 'edit_page', $post_id ) )
        return $post_id;
  }
  else
  {
    if ( !current_user_can( 'edit_post', $post_id ) )
        return $post_id;
  }

  // OK, we're authenticated: we need to find and save the data

  $mydata = $_POST['myplugin_new_field'];

  // Do something with $mydata 
  // probably using add_post_meta(), update_post_meta(), or 
  // a custom table (see Further Reading section below)

   return $mydata;
}

All of your routines to valid data will be done within this function. In the end, you will likely save the data using something like: update_post_meta('meta_key', 'meta_value');

EDIT: I realize I did not address the breadth of your question, but since I put the time into this I leave it here to get you a quarter of the way there.

1

There's really no suitable way to validate a date field, all you can do is split it up and check it in parts..

There's checkdate(), but as mentioned in the comments on the docs page it cannot be used as an effective means to sanitizing date input..

First thing i usually check is the type of data, if expecting a string then cast to a string and likewise for integer and array values.

// Casting example
$string = (string) $string;
$num = (int) $num;
$array = (array) $array;

For date fields you typically have a seperator between each part of the date, split based on that and cast the parts(however many you're expecting) as integers.

$date = explode( '/', (string) $string );
$date = array_map( 'intval', $date );
// Now count the parts and validate them further - eg. you don't want negative values

Of course this really depends how you store the date and what you're expecting in that field, it's something you'll just have to sanitize appropriately according to your specific needs.

Numeric values are quite easy, first cast to int..

$num = (int) $var_with_num;
// Or
$num = absint( $var_with_expected_non_negative_num ); // absint is a WordPress function

Then check it's within your given range(per your question).

// If it's not in range
if( $num < 100 || $num > 500 ) {
    // Number is not in range
}

or..

// If it is in range - including 100 & 500 as possible values
if( $num >= 100 && $num <= 500 ) {
    // Number is in range
}

Checking if a string is a particular length is easy, so easy in fact i'm just going to link you to the PHP documention for strlen.

http://php.net/manual/en/function.strlen.php

The date values are the most tricky in my opinion, but really it's a case of writing your code to suit what you expect from that field. If you have a field with a date format of D/M/Y for example you know that the / (forward slash) will(should) be present and that splitting on that delimeter should give you an array of 3 numeric values... (if the split doesn't give you 3 values, or any aren't valid numeric values, then the data was invalid)..

Hope that helps.. (and i'm open to critique if anyone has a better method for any of the above).

1

To properly validate input, you will need to use a combination of Javascript and PHP.

I highly recommend using the jQuery Validation plugin: http://docs.jquery.com/Plugins/Validation. It will let you validate the inputs immediately and provide feedback to the user that something is wrong.

The second step is to validate the data using PHP. WordPress has a bunch of built-in validation functions, so I'd start there and if you can't find what you need simply build in the logic that you need.

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.