WP_REST_Request::has_valid_params()

Checks whether this request is valid according to its attributes.


Description Description


Return Return

(bool|WP_Error) True if there are no parameters to validate or if all pass validation, WP_Error if required parameters are missing.


Top ↑

Source Source

File: wp-includes/rest-api/class-wp-rest-request.php

	public function has_valid_params() {
		// If JSON data was passed, check for errors.
		$json_error = $this->parse_json_params();
		if ( is_wp_error( $json_error ) ) {
			return $json_error;
		}

		$attributes = $this->get_attributes();
		$required   = array();

		// No arguments set, skip validation.
		if ( empty( $attributes['args'] ) ) {
			return true;
		}

		foreach ( $attributes['args'] as $key => $arg ) {

			$param = $this->get_param( $key );
			if ( isset( $arg['required'] ) && true === $arg['required'] && null === $param ) {
				$required[] = $key;
			}
		}

		if ( ! empty( $required ) ) {
			return new WP_Error(
				'rest_missing_callback_param',
				/* translators: %s: List of required parameters. */
				sprintf( __( 'Missing parameter(s): %s' ), implode( ', ', $required ) ),
				array(
					'status' => 400,
					'params' => $required,
				)
			);
		}

		/*
		 * Check the validation callbacks for each registered arg.
		 *
		 * This is done after required checking as required checking is cheaper.
		 */
		$invalid_params = array();

		foreach ( $attributes['args'] as $key => $arg ) {

			$param = $this->get_param( $key );

			if ( null !== $param && ! empty( $arg['validate_callback'] ) ) {
				$valid_check = call_user_func( $arg['validate_callback'], $param, $this, $key );

				if ( false === $valid_check ) {
					$invalid_params[ $key ] = __( 'Invalid parameter.' );
				}

				if ( is_wp_error( $valid_check ) ) {
					$invalid_params[ $key ] = $valid_check->get_error_message();
				}
			}
		}

		if ( $invalid_params ) {
			return new WP_Error(
				'rest_invalid_param',
				/* translators: %s: List of invalid parameters. */
				sprintf( __( 'Invalid parameter(s): %s' ), implode( ', ', array_keys( $invalid_params ) ) ),
				array(
					'status' => 400,
					'params' => $invalid_params,
				)
			);
		}

		return true;

	}

Top ↑

Changelog Changelog

Changelog
Version Description
4.4.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.