WP_Ability::validate_input( mixed $input = null ): true|WP_Error

In this article

Validates input data against the input schema.

Parameters

$inputmixedoptional
The input data to validate.

Default:null

Return

true|WP_Error Returns true if valid or the WP_Error object if validation fails.

Source

public function validate_input( $input = null ) {
	$input_schema = $this->get_input_schema();
	if ( empty( $input_schema ) ) {
		if ( null === $input ) {
			return true;
		}

		return new WP_Error(
			'ability_missing_input_schema',
			sprintf(
				/* translators: %s ability name. */
				__( 'Ability "%s" does not define an input schema required to validate the provided input.' ),
				$this->name
			)
		);
	}

	$valid_input = rest_validate_value_from_schema( $input, $input_schema, 'input' );
	if ( is_wp_error( $valid_input ) ) {
		$is_valid = new WP_Error(
			'ability_invalid_input',
			sprintf(
				/* translators: %1$s ability name, %2$s error message. */
				__( 'Ability "%1$s" has invalid input. Reason: %2$s' ),
				$this->name,
				$valid_input->get_error_message()
			)
		);
	} else {
		$is_valid = true;
	}

	/**
	 * Filters the input validation result for an ability.
	 *
	 * Allows developers to add custom validation logic on top of the default
	 * JSON Schema validation. If default validation already failed, the filter
	 * receives the WP_Error object and can add additional error information or
	 * override it. If default validation passed, the filter can add additional
	 * validation checks and return a WP_Error if those checks fail.
	 *
	 * @since 7.1.0
	 *
	 * @param true|WP_Error $is_valid     The validation result from default validation.
	 * @param mixed         $input        The input data being validated.
	 * @param string        $ability_name The name of the ability.
	 */
	$validity = apply_filters( 'wp_ability_validate_input', $is_valid, $input, $this->name );
	if ( false === $validity ) {
		return new WP_Error( 'ability_invalid_input', __( 'Invalid input.' ) );
	}
	if ( is_wp_error( $validity ) && $validity->has_errors() ) {
		return $validity;
	}
	return true;
}

Hooks

apply_filters( ‘wp_ability_validate_input’, true|WP_Error $is_valid, mixed $input, string $ability_name )

Filters the input validation result for an ability.

Changelog

VersionDescription
6.9.0Introduced.

User Contributed Notes

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