Error in Validate Field with ACF plugin in WordPress

I have the following problem when I am validating a field with the Advanced Custom Fields plugin in wordpress. What happens is that the field is validated correctly but the error appears on a new page instead of going out on the same page above the field to which I am validating. The code to validate is the following:

function validate_fields_contact()
{
    add_filter('acf/validate_value/name=phone_contact', 'validate_phone_number', 10, 4);
}

function validate_phone_number($valid, $value, $field, $input)
{
    if (!$valid) {
        return $valid;
    }

    if(!preg_match("/^\+XX(\s|\d){8,12}$/", $value)) {
        return __('Incorrect Format.');
    }

    return true;
}

It should be like that:

enter image description here

This is what happens

enter image description here

2 Answers
2

I did have the same issue. And I wasted enough time for the answer.

At first be sure that:

The ajax request isn’t failed and happens. So, check:

  1. Is acf_form_head() before get_header() and run before any html is output?
  2. Does your theme contain call to wp_head()?
  3. Does your theme contain call to wp_foot()?
  4. Are your deferring the loading of JavaScript or otherwise altering the way that JavaScript is loaded on the page?

(Look at this ACF support topic too. If you use acf_form() for creating new user look at this topic).

But in my case the root was is_admin() in this line into the ‘acf/validate_value’ hook:

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

Because is_admin() returns ‘true’ by AJAX requests. As a result, the validate function didn’t work.

Hope it will helpfully for somebody.

Leave a Comment