Automattic\WooCommerce\Blocks\Domain\Services

CheckoutFields::validate_field_for_location()publicWC 1.0

Validates a field to check it belongs to the given location and is valid according to its registration.

This does not apply any custom validation rules on the value.

Method of the class: CheckoutFields{}

No Hooks.

Return

true|WP_Error. True if the field is valid, a WP_Error otherwise.

Usage

$CheckoutFields = new CheckoutFields();
$CheckoutFields->validate_field_for_location( $key, $value, $location );
$key(string) (required)
The field key.
$value(mixed) (required)
The field value.
$location(string) (required)
The location to validate the field for (address|contact|order).

CheckoutFields::validate_field_for_location() code WC 9.0.1

public function validate_field_for_location( $key, $value, $location ) {
	if ( 'additional' === $location ) {
		wc_deprecated_argument( 'location', '8.9.0', 'The "additional" location is deprecated. Use "order" instead.' );
		$location = 'order';
	}

	if ( ! $this->is_field( $key ) ) {
		return new WP_Error(
			'woocommerce_invalid_checkout_field',
			\sprintf(
			// translators: % is field key.
				__( 'The field %s is invalid.', 'woocommerce' ),
				$key
			)
		);
	}

	if ( ! in_array( $key, $this->fields_locations[ $location ], true ) ) {
		return new WP_Error(
			'woocommerce_invalid_checkout_field_location',
			\sprintf(
			// translators: %1$s is field key, %2$s location.
				__( 'The field %1$s is invalid for the location %2$s.', 'woocommerce' ),
				$key,
				$location
			)
		);
	}

	$field = $this->additional_fields[ $key ];
	if ( ! empty( $field['required'] ) && empty( $value ) ) {
		return new WP_Error(
			'woocommerce_required_checkout_field',
			\sprintf(
			// translators: %s is field key.
				__( 'The field %s is required.', 'woocommerce' ),
				$key
			)
		);
	}

	return true;
}