Search code examples
wordpressninja-forms

Custom validation Ninja form with error handle


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?


Solution

  • 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;
    }