rest_validate_string_value_from_schema

函数
rest_validate_string_value_from_schema ( $value, $args, $param )
参数
  • (mixed) $value The value to validate.
    Required:
  • (array) $args Schema array to use for validation.
    Required:
  • (string) $param The parameter name, used in error messages.
    Required:
返回值
  • (true|WP_Error)
定义位置
相关方法
rest_validate_integer_value_from_schemarest_validate_value_from_schemarest_validate_null_value_from_schemarest_validate_array_value_from_schemarest_validate_number_value_from_schema
引入
5.7.0
弃用
-

rest_validate_string_value_from_schema: 这是一个WordPress函数,用于验证一个字符串值是否与模式相匹配: 该函数接收一个字符串参数和一个模式参数,如果字符串值与模式不匹配,则返回一个错误信息。

根据schema来验证一个字符串值。

function rest_validate_string_value_from_schema( $value, $args, $param ) {
	if ( ! is_string( $value ) ) {
		return new WP_Error(
			'rest_invalid_type',
			/* translators: 1: Parameter, 2: Type name. */
			sprintf( __( '%1$s is not of type %2$s.' ), $param, 'string' ),
			array( 'param' => $param )
		);
	}

	if ( isset( $args['minLength'] ) && mb_strlen( $value ) < $args['minLength'] ) {
		return new WP_Error(
			'rest_too_short',
			sprintf(
				/* translators: 1: Parameter, 2: Number of characters. */
				_n(
					'%1$s must be at least %2$s character long.',
					'%1$s must be at least %2$s characters long.',
					$args['minLength']
				),
				$param,
				number_format_i18n( $args['minLength'] )
			)
		);
	}

	if ( isset( $args['maxLength'] ) && mb_strlen( $value ) > $args['maxLength'] ) {
		return new WP_Error(
			'rest_too_long',
			sprintf(
				/* translators: 1: Parameter, 2: Number of characters. */
				_n(
					'%1$s must be at most %2$s character long.',
					'%1$s must be at most %2$s characters long.',
					$args['maxLength']
				),
				$param,
				number_format_i18n( $args['maxLength'] )
			)
		);
	}

	if ( isset( $args['pattern'] ) && ! rest_validate_json_schema_pattern( $args['pattern'], $value ) ) {
		return new WP_Error(
			'rest_invalid_pattern',
			/* translators: 1: Parameter, 2: Pattern. */
			sprintf( __( '%1$s does not match pattern %2$s.' ), $param, $args['pattern'] )
		);
	}

	return true;
}

常见问题

FAQs
查看更多 >