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. Commented Mar 29, 2018 at 8:29
  • Yeah minimum and maximum are for numeric parameters, not strings. 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
  • I understood this was possible but was trying to use the built in method. I'll try a mixture of the built in and custom. Commented Mar 29, 2018 at 8:31
  • 1
    In WP 5.5.0 support for maxLength and minLength are added. core.trac.wordpress.org/browser/tags/5.5.1/src/wp-includes/… Commented Nov 29, 2020 at 13:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.