Home › Forums › Front-end Issues › Trigger verification of the form without submitting it
How can I trigger the verification of an acf_form()
?
I have a form divided in two parts, and I want to check if the fields of the first part are correctly filled before displaying the second part.
<div id="form-part-1">
<!-- inputs -->
<a href="#">Continue</a>
</div>
<div id="form-part-2">
<!-- inputs -->
</div>
I’ve used the checkValidity()
JS function.
$('#form-part-1 button.input-submit').click(function(e) {
e.preventDefault();
var valid = true;
$('#form-part-1').find('input').each(function() {
if (valid === true) {
valid = this.checkValidity();
}
});
if (valid === true) {
$('.acf-error-message').remove();
$('#form-part-2').show();
$('#form-part-1').slideUp();
}
});
This isn’t perfect, and it don’t use acf/validate_value
or acf/validate_save_post
, but I can’t manage to use them with the ACF Javascript API
This solution lack of few ACF functionality. For example an image field will be valid for any type of files.
An inelegant solution would be to watch for ACF errors messages in the current step before displaying the next one.
There is an entirely new JS API for ACF https://www.advancedcustomfields.com/resources/javascript-api/
Reading through this it seems that what you want to do should be possible, but since it is so new you’re going to be mostly on your own figuring it out.
Okay, I’ll try to figure it out later. If I do, I’ll document it here !
Hey ninobysa,
I am still working on my multistep form, i realized that i would need to create my own validation.
$(".nextone").click(function(e){
e.preventDefault();
$.ajax({
dataType: 'json',
type: 'POST',
url: ajaxurl,
data: {
action: 'epm_registration_process',
epformdata: $('#field-group-1 input, #field-group-1 select').serialize()
},
success: function(resp) {
if (resp === true) {
//successful validation
if(animating) return false;
animating = true;
current_fs = $(this).parent();
next_fs = $(this).parent().next();
//activate next step on progressbar using the index of next_fs
$("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");
//show the next fieldset
next_fs.show();
//hide the current fieldset with style
current_fs.animate({opacity: 0}, {
step: function(now, mx) {
//as the opacity of current_fs reduces to 0 - stored in "now"
//1. scale current_fs down to 80%
scale = 0.8 + (1 - now) * 0.2;
//2. bring next_fs from the right(50%)
left = (now * 50)+"%";
//3. increase opacity of next_fs to 1 as it moves in
opacity = 1 - now;
/*current_fs.css({
'transform': 'scale('+scale+')',
'position': 'absolute'
});*/
next_fs.css({'opacity': opacity});
},
duration: 0,
complete: function(){
current_fs.hide();
animating = false;
},
//this comes from the custom easing plugin
easing: 'easeInOutBack'
});
return false;
} else {
$.each(resp, function(i, v) {
console.log(i + " => " + v); // view in console for error messages
if( $('input[name="' + i + '"], select[name="' + i + '"]').hasClass('inputTxtError') ){}else{
var msg = '<div class="acf-notice -error acf-error-message"><p>'+v+'</p></div>'
$('input[name="' + i + '"], select[name="' + i + '"]').addClass('inputTxtError').before(msg);
}
});
var keys = Object.keys(resp);
$('input[name="'+keys[0]+'"]').focus();
}
return false;
},
error: function(errorThrown) {
console.log(errorThrown);
}
});
return false;
});
PHP CODE:
function epm_registration_process($post_id){
//Prepare basic user info
$username = strtolower($_POST['acf']['field_5b4be98fd288c']);
$firstname = $_POST['acf']['field_5b4be9d8d288d'];
$lastname = $_POST['acf']['field_5b4be9e8d288e'];
$email = $_POST['acf']['field_5b4be9f7d288f'];
$password = $_POST['acf']['field_5b4bea0bd2890'];
$cpassword = $_POST['acf']['field_5b4bea8bd2891'];
$error = array();
//IMPORTANT: You should make server side validation here!
if( empty($username) ){
$_SESSION['errors']['acf[field_5b4be98fd288c]'] = "Please enter a username";
}elseif(username_exists( $username )){
$_SESSION['errors']['acf[field_5b4be98fd288c]'] = "Username already exist";
}
if( empty($firstname) ){
$_SESSION['errors']['acf[field_5b4be9d8d288d]'] = "Please enter your firstname";
}
if(count($_SESSION['errors']) > 0){
//This is for ajax requests:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo json_encode($_SESSION['errors']);
exit();
}
//This is when Javascript is turned off:
echo '<ul>';
foreach($_SESSION['errors'] as $key => $value){
echo '<li>' . $value . '</li>';
}
echo '</ul>';
exit();
}else{
//form validation successful - process data here!!!!
}
}
add_action('wp_ajax_epm_registration_process', 'epm_registration_process');
add_action('wp_ajax_nopriv_epm_registration_process', 'epm_registration_process');
add_filter('acf/pre_save_post' , 'epm_registration_process', 10, 1 );
I am stuck at how can i get $_POST data if form does not submit the normal way hence i cannot validate against a user already existing in the database etc… i am only able to check if the field is empty
A POST request with a good nonce, the action acf/validate_save_post
and the fields data return valuable informations.
{
nonce: acf.o.nonce,
action: 'acf/validate_save_post',
acf[field_id1...]: 'value on the input field_id1...',
acf[field_id2...]: 'value on the input field_id2...'
}
I’ve used it that way :
$("#validation-button").click( function(e) {
e.preventDefault();
validateACFinputs($(this.form).serializeArray());
});
function validateACFinputs(form_data) {
var data = {
nonce: acf.o.nonce,
action: "acf/validate_save_post",
post_id: acf.o.post_id };
for (const i in form_data) {
data[form_data[i].name] = form_data[i].value;
}
$.post(
my_ajax_obj.ajax_url, data,
function(result) {
errors = result.data.errors
if (errors === 0) {
// Code for success
} else {
// Code for fail
}
}
);
}
(my_ajax_obj.ajax_url
contains the url of admin-ajax.php, if you don’t know what it is, please read the WordPress documentation about admin-ajax.php)
Notes :
.checkValidity()
on one of the input, because it seems to cast the whole ACF validation process.checkValidity()
.acf
but I haven’t tried it yet.This remains incomplete compared to the classical behavior when you click on the submit…
Add the errors with the proper acf function :
acf.validation.add_error(field_container, errors[i]['message']);
field_container
is the jQuery object of the .acf-field
direct parent of the .acf-input
errors[i]['message']
is the message (see how I get the errors
in my previous post)
Well, I’m embarrassed. After reading the ACF source code I’ve found a display_errors
function.
To display the errors messages you just need to add it into the callback of the POST request, like this :
$.post(
my_ajax_obj.ajax_url, data,
function(result) {
errors = result.data.errors
if (errors === 0) {
// Code for success
} else {
acf.validation.display_errors( errors, $("form.acf-form") );
}
}
);
I know this is an old thread but I was looking to do something similar. I’ve found the easiest solution to trigger acf validation early is the following:
let valid = acf.validateForm( {
form: $( '#acf-form' ),
} );
Is anyone can tell what’s the new approach or replacement for acf.validation.add_error
Seems acf.validation.add_error
not working anymore and it throwing errors. So what’s the best way to add errors or triggers errors if that field is not valid. I can do the rest like checking validation or others just unable to display the error message in front.
Maybe try:
acf.validation.addError( {
input: ‘insert_input_name_here’,
message: ‘insert message here’
} );
The topic ‘Trigger verification of the form without submitting it’ is closed to new replies.
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.