Custom validation (tokens)
-
Hello! I’ve created a token table and I’m trying to validate tokens by comparing a form table with the token table. If a token is valid, I want to mark it as used. However, the forminator_custom_form_submit_errors hook retrieves data from the database but doesn’t compare it with the tokens or mark them as used. Any advice would be greatly appreciated.
-
Hi @daianaamado564,
I hope you are doing well today!
Please provide us the code snippet you have used, so that we can check further.
Kind regards,
ZaferHi, Thank you so much for your response! I’m having trouble with this snippet code:
// Add action to validate token before form submission errors
add_action('forminator_custom_form_submit_errors', 'validate_token_before_submit_errors', 10, 2);
function validate_token_before_submit_errors($form, $response) {
// ID of the specific form
$form_id = 299;
// Check if the form is the correct one
if ($form->id != $form_id) {
return;
}
// Get the token from the text-1 field
$submitted_token = sanitize_text_field($form->get_field_value('text-1'));
if (empty($submitted_token)) {
$response['errors']['text-1'] = 'The token field is empty.';
return;
}
global $wpdb;
// Query the database to check if the token exists
$token_row = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM {$wpdb->prefix}participation_tokens WHERE token = %s",
$submitted_token
));
if ($token_row) {
if ($token_row->used == 0) {
// Mark the token as used
$update_result = $wpdb->update(
"{$wpdb->prefix}participation_tokens",
array('used' => 1),
array('token' => $submitted_token),
array('%d'),
array('%s')
);
if ($update_result === false) {
// Error updating token status
$response['errors']['text-1'] = 'Error updating token status.';
}
} else {
// Token has already been used
$response['errors']['text-1'] = 'The token has already been used or is not valid.';
}
} else {
// Token not found
$response['errors']['text-1'] = 'The token is not valid.';
}
}- This reply was modified 2 months, 3 weeks ago by daianaamado564.
Hi, Thank you so much for your response! I’m having trouble with this snippet code:
// Add action to validate token before form submission errors
add_action('forminator_custom_form_submit_errors', 'validate_token_before_submit_errors', 10, 2);
function validate_token_before_submit_errors($form, $response) {
// ID of the specific form
$form_id = 299;
// Check if the form is the correct one
if ($form->id != $form_id) {
return;
}
// Get the token from the text-1 field
$submitted_token = sanitize_text_field($form->get_field_value('text-1'));
if (empty($submitted_token)) {
$response['errors']['text-1'] = 'The token field is empty.';
return;
}
global $wpdb;
// Query the database to check if the token exists
$token_row = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM {$wpdb->prefix}participation_tokens WHERE token = %s",
$submitted_token
));
if ($token_row) {
if ($token_row->used == 0) {
// Mark the token as used
$update_result = $wpdb->update(
"{$wpdb->prefix}participation_tokens",
array('used' => 1),
array('token' => $submitted_token),
array('%d'),
array('%s')
);
if ($update_result === false) {
// Error updating token status
$response['errors']['text-1'] = 'Error updating token status.';
}
} else {
// Token has already been used
$response['errors']['text-1'] = 'The token has already been used or is not valid.';
}
} else {
// Token not found
$response['errors']['text-1'] = 'The token is not valid.';
}
}Thanks for response!
You are using “forminator_custom_form_submit_errors” hook incorrectly, I’m afraid. There are two main issues here:
1. It’s a filter hook, not action hook – so it is required for it to return data. It needs to return the errors.
2. The set of callback function attributes is incomplete and in wrong order. The filter is called like this:
self::$submit_errors = apply_filters( 'forminator_custom_form_submit_errors', self::$submit_errors, self::$module_id, self::$info['field_data_array'] );
so your “validate_token_before_submit_errors” callback function should be used like this
add_action('forminator_custom_form_submit_errors', 'validate_token_before_submit_errors', 10, 3); function validate_token_before_submit_errors($errors, $form_id, $form_data) { // here comes your custom code in which you can use // $form_id - contains form ID // $form_data - includes data submitted in the form which you can use for your comparisons // and finally, you can modify $errors array if you want to return errors return $errors; }
Note please: we don’t provide custom coding so I’m not able to provide you with a ready-to-use solution; based on above information, however, I believe you should be able to modify your code accordingly.
Kind regards,
AdamThanks for your reply! The code I ended up using worked for validating tokens and having a time limit for submissions, however now it crashes with the login and registration forms, even though I specify the id of the participation form. Maybe it’s because of those parameters you mention? It’s weird because the code works but it crashes with the other forms.
//Token validation and form limitation every 12 hours
add_filter('forminator_custom_form_submit_errors', 'limit_form_submission_with_token_validation', 10, 3);
function limit_form_submission_with_token_validation($submit_errors, $form_id, $field_data_array) {
$form_ids = array('299');
$cookie_name = 'form_' . $form_id . '_last_submit';
// TIME VALIDATION
if (in_array($form_id, $form_ids)) {
if (isset($_COOKIE[$cookie_name])) {
$last_submit = strtotime($_COOKIE[$cookie_name]);
$time_now = time();
$time_limit = 12 * 60 * 60;
if (($time_now - $last_submit) < $time_limit) {
// We stop validation here if the time limit has not passed
$submit_errors[] = __('Solo puedes enviar este formulario una vez cada 12 horas.');
return $submit_errors; // If time validation fails, we stop execution
}
} else {
setcookie($cookie_name, date('Y-m-d H:i:s'), time() + (12 * 60 * 60), "/");
}
}
// TOKEN VALIDATION (only runs if time validation passes)
$submitted_token = null;
foreach ($field_data_array as $field_data) {
if ($field_data['name'] == 'text-1') {
$submitted_token = sanitize_text_field($field_data['value']);
break;
}
}
if (empty($submitted_token)) {
$submit_errors[] = __('El campo de token está vacío.');
return $submit_errors;
}
global $wpdb;
$token_row = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM {$wpdb->prefix}participation_tokens WHERE token = %s",
$submitted_token
));
if ($token_row) {
if ($token_row->used == 0) {
// Mark the token as used only if it passes both validations
$update_result = $wpdb->update(
"{$wpdb->prefix}participation_tokens",
array('used' => 1),
array('token' => $submitted_token),
array('%d'),
array('%s')
);
if ($update_result === false) {
$submit_errors[] = __('Error al actualizar el estado del token.');
}
} else {
$submit_errors[] = __('El token ya ha sido utilizado o no es válido.');
}
} else {
$submit_errors[] = __('El token no es válido.');
}
return $submit_errors;}
Hi @daianaamado564,
When I try the given code in my system it doesn’t work with any form. Seems like the issue is more with how you are returning the value.
It should be as following example:
$submit_errors[]['submit'] = 'your error message';
Or if you want to display the validation message for the text-1 field it should be as:
$submit_errors[]['text-1'] = 'your error message';
Please do check and see how that goes.
Kind Regards,
Nithin
Hi, thanks again for your response!
Even though I specified the ID of the form the code was supposed to affect, I couldn’t find a way to make the code not affect all my forms, so I just managed the login and registration forms with another plugin, limiting Forminator to the form that needed the code, and now everything works.
Thanks a lot for your time and work.
Regards.
Hi @daianaamado564,
We are glad to hear that the issue has been resolved. I’ll go and mark this thread as resolved. If you have any additional questions or require further help, please let us know!
Kind regards,
Zafer
- You must be logged in to reply to this topic.