Make WordPress Core

Opened 5 years ago

Closed 5 years ago

Last modified 5 years ago

#47906 closed enhancement (duplicate)

REST API validation schema should support regular expressions for strings.

Reported by: manzoorwanijk's profile manzoorwani.jk Owned by:
Milestone: Priority: normal
Severity: normal Version:
Component: REST API Keywords:
Focuses: rest-api Cc:

Description

Currently, the default validation schema (for strings) is limited to type, enum and format (date-time, email & ip). It would be useful to have RegEx support out of the box. So, instead of just

<?php
if ( 'string' === $args['type'] && ! is_string( $value ) ) {
        return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'string' ) );
}

we can do like this

<?php
if ( 'string' === $args['type'] ) {
        if ( ! is_string( $value ) ) {
                return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'string' ) );
        }
        if ( isset( $args['matches'] ) && ! preg_match( $args['matches'], $value ) ) {
                return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s does not match the pattern.' ), $param ) );
        }
}

This way, we can specify the schema like this

<?php
array(
        'methods'  => WP_REST_Server::CREATABLE,
        'callback' => 'some_callback',
        'args'     => array(
                'id' => array(
                        'type'     => 'string',
                        'required' => true,
                        'matches'  => '/\A[a-z0-9_]{1,32}\Z/i',
                ),
        ),
)

Change History (2)

#1 @TimothyBlynJacobs
5 years ago

  • Milestone Awaiting Review deleted
  • Resolution set to duplicate
  • Status changed from new to closed

Hi @manzoorwanijk,

Thanks for the ticket!

We're already tracking this in #44949

#2 @manzoorwani.jk
5 years ago

@TimothyBlynJacobs that's great!

Note: See TracTickets for help on using tickets.