I have a cred form which has multiple sets of repeating field groups (latest beta) within it. I want to require the user to enter a minimum number of entries in each of the groups.
I am following the example here: https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_validate
I have come up with the following code, but it doesn't display any errors anywhere on the page or in the console, and it doesn't prevent submission of the form. I don't know what I am missing.
add_filter('cred_form_validate','my_validation',10,2);
function my_validation($error_fields, $form_data)
{
list($fields,$errors)=$error_fields;
if ($form_data['id']==157)
{
$user = get_current_user_id();
$user_post_count = count_user_posts( $user , 'reference' );
if ( $user_post_count < 3)
{
//set error message for my_field
$errors['wpcf-user-validation']='Please add at least 3 references.';
}
}
return array($fields,$errors);
}
Any help is appreciated.
Hello,
For the question:
it doesn't display any errors anywhere on the page or in the console, and it doesn't prevent submission of the form.
The problem might in the CRED form settings, please try these:
1) You are using Types plugin to setup the custom field "user-validation"
2) Edit the CRED form (ID 157), put above custom fields into the CRED form, for example:
[cred_field field='user-validation' ...]
Then test again.
Thank you Luo, I have added the field to the group and inserted it in my form. The form still submits normally and no errors are displayed. You can see an example here:
hidden link
OK, i found I had some old code in my functions.php rather than the code I shared above. The code above does indeed prevent form submission and show the error on the field 'user-validation'.
However, I need to have the function check how many entries I have in my repeating field group named 'references', rather than the user-validation field. Also, my code doesn't check that the entries are children of the current post, only how many posts of that type exist, which could be problematic.
I think the question here is how to count the entries in the new repeating field groups.
I wound up using jQuery to do this instead of doing it on PHP. Here's my code:
$(document).ready(function(){
var count = $(".references").length;
var count2 = $(".emergency-contacts").length;
if (count < 3){
$("input[name='form_submit_1']").attr("disabled", true);
$("input[name='form_submit_1']").addClass("disabled");
$(".submit-warning").css("display","block")
}
if (count2 < 1){
$("input[name='form_submit_1']").attr("disabled", true);
$("input[name='form_submit_1']").addClass("disabled");
$(".submit-warning").css("display","block")
}
});
I added my own div for a custom warning message div (.submit-warning) which is display:none by default.