Support

Account

Home Forums Add-ons Repeater Field Validation for Date Range

Solving

Validation for Date Range

  • I have two repeater date field, “start_date” and “end_date”. Is it possible to validate the “end_date” to be greater than the “start_date”?

    Thanks in advance

  • Yes, it is

    
    add_filter('acf/validate_value/name=end_date', 'validate_end_date_func', 10, 4);
    function validate_end_date_func($valid, $value, $field, $input) {
      if (!$valid) {
        return $valid;
      }
      $repeater_key = 'field_56faad2a333ab';
      $start_key = 'field_56fab49fd51ce';
      $end_key = 'field_56fab4d1d51d0';
      // extract row from input
      $row = preg_replace('/^\s*acf\[[^\]]+\]\[([^\]]+)\].*$/', '\1', $input);
      $start_value = $_POST['acf'][$repeater_key][$row][$start_key];
      $end_value = $value;
      if ($end_value <= $start_value) {
       $valid = 'end value must be greater than start value';
      }
      return $valid
    }
    
  • Hi John,

    Thanks for your response. I copied your code and updated the following parts to match mine:

    
    name
    $repeater_key
    $start_key
    $end_key
    

    I tried to place the code in the allotted text editor for validated fields in admin dashboard and also tried to place it in my functions.php. But it didn’t catch the error. But it can detect some php syntax error.

  • There’s a semicolon missing near the end. There’s no syntax checker here and I just type code straight into the message most of the time assuming that people can correct minor syntax errors when needed.

    
    add_filter('acf/validate_value/name=end_date', 'validate_end_date_func', 10, 4);
    function validate_end_date_func($valid, $value, $field, $input) {
      if (!$valid) {
        return $valid;
      }
      $repeater_key = 'field_56faad2a333ab';
      $start_key = 'field_56fab49fd51ce';
      $end_key = 'field_56fab4d1d51d0';
      // extract row from input
      $row = preg_replace('/^\s*acf\[[^\]]+\]\[([^\]]+)\].*$/', '\1', $input);
      $start_value = $_POST['acf'][$repeater_key][$row][$start_key];
      $end_value = $value;
      if ($end_value <= $start_value) {
       $valid = 'end value must be greater than start value';
      }
      return $valid;
    }
    
  • Does this work as well without the fields IDs (like field_56faad2a333ab) but with field names?

  • @chapper, no, this does not work with field names. When doing validation you must access the values in $_POST[‘acf’] and ACF uses field keys here.

Viewing 6 posts - 1 through 6 (of 6 total)

The topic ‘Validation for Date Range’ is closed to new replies.