#47906 closed enhancement (duplicate)
REST API validation schema should support regular expressions for strings.
Reported by: | 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)
Note: See
TracTickets for help on using
tickets.
Hi @manzoorwanijk,
Thanks for the ticket!
We're already tracking this in #44949