acf/validate_value

Overview

This filter allows you to perform custom validation on a field’s value and either allow or prevent the post from being saved.

Changelog

  • Added in v5.0.0

Parameters

Name Type Description
$valid mixed Whether or not the value is valid (true / false). Can also be returned as a custom error message (string)
$value mixed The value to be saved
$field array An array containing all the field settings
$input string the DOM element’s name attribute

Usage

There are 4 ways to hook into this filter:

  1. acf/validate_value – filter for every field
  2. acf/validate_value/type={$field_type} – filter for a specific field based on itโ€™s type
  3. acf/validate_value/name={$field_name} – filter for a specific field based on itโ€™s name
  4. acf/validate_value/key={$field_key} – filter for a specific field based on itโ€™s key

This example will validate the width of a selected image. If the image width is less than 960px, a message will be returned and displayed causing the post validation to fail.

functions.php

add_filter('acf/validate_value/name=validate_this_image', 'my_acf_validate_value', 10, 4);

function my_acf_validate_value( $valid, $value, $field, $input ){
	
	// bail early if value is already invalid
	if( !$valid ) {
		
		return $valid;
		
	}
	
	
	// load image data
	$data = wp_get_attachment_image_src( $value, 'full' );
	$width = $data[1];
	$height = $data[2];
	
	if( $width < 960 ) {
		
		$valid = 'Image must be at least 960px wide';
		
	}
	
	
	// return
	return $valid;
	
	
}
Screenshot of validation result

Screenshot of validation result

Related

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.