1

I have two date fields where I want to make sure the "end date" is always later than the "start date".

I added a validation function per ACF's documentation. It does fire, but the custom message does not display next to the field. It only says "validation failed" on the top.

add_action('acf/validate_save_post', 'my_acf_validate_save_post');

function my_acf_validate_save_post()
{

    $start = $_POST['acf']['field_5fb0e816ea4fc'];
    $start = new DateTime($start);

    $end = $_POST['acf']['field_5fb0e83aea4fd'];
    $end = new DateTime($end);

    // check custom $_POST data
        if ($start > $end) {
            acf_add_validation_error('event_series_end_date', 'End Date should be later than the Start Date');
        }
}

1 Answer 1

1

Add this snippet and check according to your needed.

add_action('acf/validate_save_post', 'my_acf_validate_save_post');
    
    function my_acf_validate_save_post()
    {
    
        $start = $_POST['acf']['field_5fb0e816ea4fc'];
        //$start = new DateTime($start);
        $start = strtotime($start);
    
        $end = $_POST['acf']['field_5fb0e83aea4fd'];
        //$end = new DateTime($end);
        $end = strtotime($end);
    
        if( current_user_can('manage_options') ) {
    
            acf_reset_validation_errors();
        
        }
    
        // check custom $_POST data
        if ($start > $end ) {

            acf_add_validation_error($_POST['acf']['field-600e609de8ab8'], 'End Date should be later than the Start Date');

         }else if ($start == $end ) { 
        
            acf_add_validation_error($_POST['acf']['field-600e609de8ab8'], 'End Date should be equal to the Start Date');

    }
    }

Screenshot in Error : enter image description here

3
  • That worked! Thanks, can you explain what is the field-600e609de8ab8? That's not a field key for either startdate or enddate, so I'm not sure why it works.
    – geochanto
    Commented Feb 7, 2021 at 21:56
  • 1
    This is field key for save and update data of Custom field & Each value saved in the database is given a ‘reference’ of the field’s key. This allows ACF to connect a value with its field
    – HK89
    Commented Feb 8, 2021 at 5:39
  • thanks! seems a bit weird that they have an arbitrary key for something like this, instead of using some generic alias. I'd hope they don't make changes to this when they make plugin version updates :D
    – geochanto
    Commented Feb 8, 2021 at 6:40

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.