Automattic\WooCommerce\Blocks\Domain\Services

CheckoutFields::get_validate_callbackpublicWC 1.0

Returns the validate callback for a given field.

Method of the class: CheckoutFields{}

No Hooks.

Returns

callable. The validate callback.

Usage

$CheckoutFields = new CheckoutFields();
$CheckoutFields->get_validate_callback( $field, $document_object );
$field(array) (required)
The field.
$document_object(DocumentObject|null)
The document object.
Default: null

CheckoutFields::get_validate_callback() code WC 9.8.5

public function get_validate_callback( $field, $document_object = null ) {
	if ( is_string( $field ) ) {
		$field = $this->additional_fields[ $field ] ?? [];
	}
	if ( $document_object && ! empty( $field['rules']['validation'] ) ) {
		return function ( $field_value, $field ) use ( $document_object ) {
			$errors = new WP_Error();

			// Only validate if we have a field.
			if ( ! $field ) {
				return true;
			}

			// Evaluate custom validation schema rules on the field.
			$validate_result = $this->is_valid_field( $field, $document_object );

			if ( is_wp_error( $validate_result ) ) {
				/* translators: %s: is the field label */
				$error_message = sprintf( __( 'Please provide a valid %s', 'woocommerce' ), $field['label'] );
				$error_code    = 'woocommerce_invalid_checkout_field';
				$errors->add( $error_code, $error_message );
			}

			return $errors->has_errors() ? $errors : true;
		};
	}
	return $field['validate_callback'] ?? null;
}