Custom validation Ninja form with error handle

只谈情不闲聊 提交于 2021-02-08 08:07:42

问题


I'm using Ninja Form plugin in my WordPress installation.

My form has 3 input text fields.

I need, after pressing the submit button, to validate one of this input by checking if the entered value exists in a custom table in my database.

If the value doesn't already exists nothing should happen (Ninja Form save the form), if it exists I need to add a Ninja Form error and let the user change the input in order to save the form with a new value.

How can I hook the submit action? How can I get in this hook the input value I need? How can I add a Ninja Form error if the value exists in order to prevent the form save?


回答1:


You can do this using the ninja_forms_submit_data hook. There you can access the value of a field using its id through the variable $form_data. When adding an error message for the field to $form_data['errors'] the form will not be saved.

Like this (in functions.php):

add_filter('ninja_forms_submit_data', 'custom_ninja_forms_submit_data');
function custom_ninja_forms_submit_data($form_data)
{
    $field_id = 2;
    $field_value = $form_data['fields'][$field_id]['value'];

    $exists = true; // Check your database if $field_value exists

    if($exists)
    {
        $form_data['errors']['fields'][$field_id] = 'Value already exists';
    }

    return $form_data;
}


来源:https://stackoverflow.com/questions/48063223/custom-validation-ninja-form-with-error-handle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!