rest_validate_enum() WordPress Function

The rest_validate_enum() function is used to check whether a value is within a specified array of values. If the value is not within the array, an error is returned. This function is useful for validating user input.

rest_validate_enum( mixed $value, array $args, string $param ) #

Validates that the given value is a member of the JSON Schema “enum”.


Parameters

$value

(mixed)(Required)The value to validate.

$args

(array)(Required)The schema array to use.

$param

(string)(Required)The parameter name, used in error messages.


Top ↑

Return

(true|WP_Error) True if the "enum" contains the value or a WP_Error instance otherwise.


Top ↑

Source

File: wp-includes/rest-api.php

function rest_validate_enum( $value, $args, $param ) {
	$sanitized_value = rest_sanitize_value_from_schema( $value, $args, $param );
	if ( is_wp_error( $sanitized_value ) ) {
		return $sanitized_value;
	}

	foreach ( $args['enum'] as $enum_value ) {
		if ( rest_are_values_equal( $sanitized_value, $enum_value ) ) {
			return true;
		}
	}

	$encoded_enum_values = array();
	foreach ( $args['enum'] as $enum_value ) {
		$encoded_enum_values[] = is_scalar( $enum_value ) ? $enum_value : wp_json_encode( $enum_value );
	}

	if ( count( $encoded_enum_values ) === 1 ) {
		/* translators: 1: Parameter, 2: Valid values. */
		return new WP_Error( 'rest_not_in_enum', wp_sprintf( __( '%1$s is not %2$s.' ), $param, $encoded_enum_values[0] ) );
	}

	/* translators: 1: Parameter, 2: List of valid values. */
	return new WP_Error( 'rest_not_in_enum', wp_sprintf( __( '%1$s is not one of %2$l.' ), $param, $encoded_enum_values ) );
}


Top ↑

Changelog

Changelog
VersionDescription
5.7.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.