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;
    }
    
Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.