5

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

3
  • 2
    why do you think such validation option exists? You will probably need to write your own validation. Commented Mar 29, 2018 at 7:09
  • I thought given the existing validation rules (minimum, maximum, enum) I've been able to use from the link I provided that perhaps maxLength was also an option but as there is no documentation that I could find. Thought it would be more economic than writing my own validation functions. I will try a mixture.
    – AndyW
    Commented Mar 29, 2018 at 8:29
  • Yeah minimum and maximum are for numeric parameters, not strings.
    – swissspidy
    Commented Mar 29, 2018 at 8:38

1 Answer 1

6

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/

2

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.