What’s the right way to validate JSON data coming from an AJAX POST request?

Question

I’m building a little plugin with a send button: when clicked, the button calls (from the admin area) a rest api endpoint, passing JSON data through AJAX. Everything works very well and the callback correctly receives the JSON data.

Now, I want to validate the data using the validate_callback function.

Problem is I only could find examples where they validate an API parameter, and I have no parameter in my API.

A typical example:

 add_action( 'rest_api_init', function () {
        register_rest_route( 'myplugin/v1', '/author/(?P<id>d+)', array(
            'methods' => 'GET',
            'callback' => 'my_awesome_func',
            'args' => array(
                'id' => array(
                    'validate_callback' => 'my_validation'
                ),
            ),
        ) );
    } );
    
    function my_validation (WP_REST_Request $request) {
       return is_numeric( $request['id'] ); 
    }

Here the developer is validating the id parameter, for example.

This is another example, from the official docs:

add_action( 'rest_api_init', function () {
  register_rest_route( 'myplugin/v1', '/author/(?P<id>d+)', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
    'args' => array(
      'id' => array(
        'validate_callback' => function($param, $request, $key) {
          return is_numeric( $param );
        }
      ),
    ),
  ) );
} );

What if I have no parameter at all but I still want to validate the request content?

0
, , , , Life after Guest 1 year 2020-07-22T03:10:23-05:00 0 Answers 80 views 0

Leave an answer

Browse
Browse