Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

We have a custom post type in our plugin and now i must provide the user a meta box where he enters latitude and longitude. I want them to be floats, i have no problems in doing the validation client side, but i don't know how i should handle server side validation in wordpress.

I thought that there was some API for doing this, but this is not the case, so i was just wandering how should i handle things inside my save function.

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

Not shure if this isn´t a general php question...

Use the WP_Error Class.

// http://php.net/manual/de/function.is-float.php
// http://php.net/manual/de/function.is-int.php
// inside your save_post/update_post hooks callback function,
// just type cast to float. You could also do a check if it contains non numeric chars
// and then simply return;
$check = ! is_float( $value ) OR ! is_int( $value ) ? new WP_Error( 'wrong value', __(" I've fallen and can't get up", 'YOUR_TEXTDOMAIN_STRING' ), $value ) : $value;

At the end of your function, check if you got an error. To provide a meaningful error message, use jQuery:

if ( is_wp_error( $check ) )
{
    $code = $check->get_error_code();
    $msg = $check->get_error_message();
    // Maybe multiple? You'll have to loop through them
    $msgs = $check->get_error_messages();

    echo "<script type='text/javascript'>
         var error = '<div id=\"message\" class=\"updated below-h2\"><p><strong>{$code}</strong> {$msg}</p></div>';
         // Append the error
         jQuery( '#icon-edit' ).after( error );
    </script>";
}
share|improve this answer
    
Yes i know that, now how do i tell wordpress "Ok, the form is invalid because the field "longitude" is not a float so don't save the values and show an error message"? :) –  Nicola Peluchetti Apr 26 '12 at 15:08
    
If i just return i don't give any kind of information on where the error is and where to show error messages –  Nicola Peluchetti Apr 26 '12 at 15:09
    
See edit with error message. –  kaiser Apr 26 '12 at 15:20
    
Ok that's what i was looking for :) –  Nicola Peluchetti Apr 26 '12 at 15:32
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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