Home › Forums › Front-end Issues › How to validate fields on the same page when using acf_form()
Hi,
I am trying to make a custom registration form that uses ACF forms for custom fields (that can be defined by the client via the ACF interface). The few fields that are mandatory for this form are the email, password, and new member’s full name.
I registered a frontend form like this:
acf_register_form([
'id' => 'new-member',
'post_id' => 'new_user',
'form' => false,
'field_groups'=> ['group_1'],
'honeypot' => true,
]);
I then built my custom HTML form as follows (please keep in mind that I stripped a lot of code for legibility):
<form method="post">
<input type="email" class="input" name="email" value="" id="email" />
<?php acf_form( 'new-member' ); ?>
<button type="submit"><?php _e( 'Register' ); ?></button>
</form>
I will use the acf/pre_save_post
hook to modify the post_id to be user_ID (once I create the user) but ACF doesn’t seem to have a hook to use for custom validation.
I managed to add some custom errors using acf/validate_save_post
and the acf_add_validation_error() function but when a user submits and the values aren’t valid they are redirected to a “Validation failed” page instead of going back on the registration page with validation errors at the top of the form.
Is there a way to validate fields and show the errors on the form instead of this middle page?
So this took quite a lot of effort to figure out. Turns out acf_form_head()
it needs to be before any output but if you do it too soon it causes all sorts of errors. I thought using WP’s init hook would work, and it did for the most part, but it would break AJAX validation (hence the middle page).
I tried a few different hooks but it seems like template_include
is the one that fixed the issue.
If you’re getting a 500 error page when an field is blank but the rest seems to work properly, try changing where your acf_form_head()
function is called.
I can’t seem to edit my original message so I’d like to add a few extra details. I get the follow error:
When I look a bit closer it seems like an ajax request is sent but gives a 500 error with the same content as above:
I don’t know if this is default ACF behaviour but it might give an idea as to what is happening. acf_form_head()
is added via the init hook so it’s not a question of not having the correct files enqueued.
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.