0

I like to set validation when both fields named species1 and species2 are no values.

I set below code on function.php. Now, validation always stops update however I set value on these field.

//ACF
function my_acf_validate_value( $valid, $value, $field, $input ){

    if( !$valid ) {
        return $valid;
    }

    $value_1 = $_POST['acf']['species1'];
    $value_2 = $_POST['acf']['species2'];

    if (empty($value_1) && empty($value_2))  {
        $valid = 'Please complete at least one of the fields';
    }

    return $valid;
}
add_filter('acf/validate_value/name=species1', 'my_acf_validate_value', 10, 4);
add_filter('acf/validate_value/name=species2', 'my_acf_validate_value', 10, 4);
6
  • I'm not that familiar with ACF but you're returning $valid regardless of the conditions, but I don't see what $valid is if the if() condition isn't met. Add a var_dump( $valid ); beneath return $valid; to see what it contains. My guess would be null. May 13, 2021 at 16:58
  • Thank you for your advise. I add var_dump( $valid ); right after return $valid;. Then it shows "bool(true) bool(true)" on white blank page when I updated article.
    – cwhiro
    May 13, 2021 at 18:34
  • I referes this information advancedcustomfields.com/resources/acf-validate_value
    – cwhiro
    May 13, 2021 at 18:35
  • Also this information support.advancedcustomfields.com/forums/topic/validate-2-fields
    – cwhiro
    May 13, 2021 at 18:36
  • So it seems to be returning true for both conditions so both values are seen as valid. So I'm not sure what's going wrong. Sorry, not familiar with what ACF is doing with these. So when you input values in both fields it returns a blank screen? May 14, 2021 at 0:16

1 Answer 1

1

I changed code like this, and it works now.

$_POST['acf']['species1'] to $_POST['acf']['field_xxxxxxxxxxxxx']

'field_xxxxxxxxxxxxx' is name that is defined by ACF itself. My mistake was setting Custom key name instead of field name.

1
  • Awesome; love to see when people figure stuff out themselves but remember to come back here and update their question. Thanks cwhiro. Remember to accept your answer as well so people know it's a viable solution. Include links to documents if you have any. :-) May 14, 2021 at 23:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.