acf_get_block_validation_state()ACF 6.3

Handle validating a block's fields and return the validity, and any errors.

This function can use values loaded into Local Meta, which means they have to be converted back to the data format before they can be validated.

No Hooks.

Returns

Array. An array containing a valid boolean, and an errors array.

Usage

acf_get_block_validation_state( $block, $using_defaults, $use_post_data, $on_load );
$block(array) (required)
An array of the block's data attribute.
$using_defaults(true|false)
True if the block is currently being generated with default values.
Default: false
$use_post_data(true|false)
True if we should validate the POSTed data rather than local meta values.
Default: false
$on_load(true|false)
True if we're validating as part of a render. This is essentially the same as a first load.
Default: false

Changelog

Since 6.3 Introduced.

acf_get_block_validation_state() code ACF 6.8.8

function acf_get_block_validation_state( $block, $using_defaults = false, $use_post_data = false, $on_load = false ) {
	$block_id = $block['id'];

	if ( $on_load && empty( $block['validate_on_load'] ) ) {
		// If we're in a page load render, and validate on load is false, skip validation.
		$errors = false;
	} elseif ( $use_post_data ) {
		$errors = acf_validate_block_from_post_data( $block );
	} elseif ( $using_defaults || empty( $block['data'] ) ) {
		// If data is empty or it's first preview, load the default fields for this block so we can get a required validation state from the current field set.
		// Treat as "on load" if it's the first render of a block.
		if ( empty( $block['validate_on_load'] ) ) {
			$errors = false;
		} else {
			$errors = acf_validate_block_from_local_meta( $block_id, acf_get_block_fields( $block ), true );
		}
	} else {
		$errors = acf_validate_block_from_local_meta( $block_id, get_field_objects( $block_id, false ), false );
	}

	return array(
		'valid'  => empty( $errors ),
		'errors' => $errors,
	);
}