WC_REST_General_Settings_V4_Controller::validate_setting_valueprivateWC 1.0

Validate a setting value before updating.

Method of the class: WC_REST_General_Settings_V4_Controller{}

No Hooks.

Returns

true|false|WP_Error. True if valid, WP_Error if invalid.

Usage

// private - for code of main (parent) class only
$result = $this->validate_setting_value( $setting_id, $value );
$setting_id(string) (required)
Setting ID.
$value(mixed) (required)
Setting value.

WC_REST_General_Settings_V4_Controller::validate_setting_value() code WC 10.3.6

private function validate_setting_value( $setting_id, $value ) {
	// Custom validation rules for specific settings.
	switch ( $setting_id ) {
		case 'woocommerce_price_num_decimals':
			if ( ! is_numeric( $value ) || $value < 0 || $value > 10 ) {
				return new WP_Error(
					'rest_invalid_param',
					__( 'Number of decimals must be between 0 and 10.', 'woocommerce' ),
					array( 'status' => 400 )
				);
			}
			break;

		case 'woocommerce_default_country':
			// Validate country code format (e.g., "US" or "US:CA").
			if ( ! empty( $value ) && ! preg_match( '/^[A-Z]{2}(:[A-Z0-9]+)?$/', $value ) ) {
				return new WP_Error(
					'rest_invalid_param',
					__( 'Invalid country/state format.', 'woocommerce' ),
					array( 'status' => 400 )
				);
			}

			if ( ! $this->validate_country_or_state_code( $value ) ) {
				return new WP_Error(
					'rest_invalid_param',
					__( 'Invalid country/state format.', 'woocommerce' ),
					array( 'status' => 400 )
				);
			}

			break;

		case 'woocommerce_allowed_countries':
			$valid_options = array( 'all', 'all_except', 'specific' );
			if ( ! in_array( $value, $valid_options, true ) ) {
				return new WP_Error(
					'rest_invalid_param',
					__( 'Invalid selling location option.', 'woocommerce' ),
					array( 'status' => 400 )
				);
			}

			break;

		case 'woocommerce_ship_to_countries':
			$valid_options = array( '', 'all', 'specific', 'disabled' );
			if ( ! in_array( $value, $valid_options, true ) ) {
				return new WP_Error(
					'rest_invalid_param',
					__( 'Invalid shipping location option.', 'woocommerce' ),
					array( 'status' => 400 )
				);
			}

			break;

		case 'woocommerce_specific_allowed_countries':
		case 'woocommerce_specific_ship_to_countries':
			if ( ! is_array( $value ) ) {
				return new WP_Error(
					'rest_invalid_param',
					__( 'Expected an array of country codes.', 'woocommerce' ),
					array( 'status' => 400 )
				);
			}

			foreach ( $value as $code ) {
				if ( ! is_string( $code ) || ! $this->validate_country_or_state_code( $code ) ) {
					return new WP_Error(
						'rest_invalid_param',
						__( 'Invalid country code in list.', 'woocommerce' ),
						array( 'status' => 400 )
					);
				}
			}
			break;
	}

	return true;
}