WordPress REST API validation

I’d like to validate the data sent to my end point.

https://www.shawnhooper.ca/2017/02/15/wp-rest-secrets-found-reading-core-code/
This post referenced the undocumented validation options. I have got 90% of what I need but now need to validate a strings length which I can’t seem to figure out.

Basically I need to say the max length is X. I tried ‘maxLength’ but that isn’t working. Has anyone done this or better yet is there any documentation on this, the post I found was quite old.

            'args' => array(
                'external_id' => array(
                    'required'      => true,
                    'type'          => 'string',
                    'description'   => 'external id',
                    'maxLength'     => 10
                )
            )

Thanks, Andy

1
1

There is no such maxLength option in the WP REST API.

You can pass a validate_callback though. Example:

<?php
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 );
                }
            ),
        ),
    ) );
} );

Source: https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/

Leave a Comment