Support

Account

Home Forums Feature Requests Validation of a field based on the value of another field Reply To: Validation of a field based on the value of another field

  • Looking back yet again because I got a notice that there was a reply, the code I posted will do nothing because the fields you’re trying to validate are part of a flex field layout. This means that they are sub fields and the ACF input will look something like

    
    $_POST['acf'] == array(
      'field_XYZ' => array( // the field key of your flex field
        // nested array for each rows
        array(
          'field_ABC' => 'first field in row',
          'field_DEF' => 'second field in row'
        ),
      ),
    );
    

    In order to validate one of these fields against the other field the first thing you need to do is find the right row.

    finding the current row

    
    // a function that finds a row in the acf input
    // that has a sub field with a specific key
    function get_current_acf_row_from_input($key, $input) {
      
      // get a list of each input index
      preg_match_all('/\[([^\]]+)\]/', $input, $matches);
      // the list of indexes will be in $matches[1]
      $matches = $matches[1];
      
      // start at the top
      $row = $_POST['acf'];
      $count = count($matches)-1;
      
      // loop over each index
      for ($i=0; $i<$count; $i++) {
        // set row to the row[index]
        $row = $row[$matches[$i]];
        // see if the field key we're looking for is in this row
        if (isset($row[$key])) {
          // it is, found it
          break;
        }
      }
      if (!isset($row[$key])) {
        // did not find a matching row
        $row = false;
      }
      
      return $row;
    } // end public function validate_condition_value
    

    Then you can modify the filter like this

    
    // conditionally require video field IF playlist ID field is blank
    add_filter('acf/validate_value/key=field_5c7ea3fd1ff26', 'acf_validate_video', 10, 4);
    
    function acf_validate_video($valid, $value, $field, $input) {
      // bail early if value is already invalid
      if( !$valid ) { return $valid; }
      
      $key = 'field_5c7ea3fd1ff26';
      $row = get_current_acf_row_from_input($key, $input);
      if ($row === false) {
        // the row was not found
        // this should not happen, but, one never knows
        return $valid;
      }
      // check that this value and the value of the other field are not both empty
      if (empty($row['field_5c8fe92190fd6']) && empty($value)) {
        $valid = __('You must select a video if no Playlist ID is defined.');
      }
      return $valid;
    }