Server Side Validation For Ninja Forms

We recently had a client who were using Ninja Forms on their site and wanted to use it’s registration module for letting users register on the website. Ninja Forms is a pretty neat plugin and it was super easy to quickly create the registration form with it.

The client also needed a validation by which a user can register only when the email was among a pre-defined list of domains. As this was the first time we were working with Ninja Forms we did not know what hooks it provided for validation.

With a quick Google search we were able to find a well laid out documentation for doing client side validation but could not find an direct way for server side validation. So we did just the frontend validation.

But this lead us to a security loop hole.

As there was no server side validation anyone could do a simple HTTP request externally and bypass the form and the validation and be able to create accounts on site with email of any domain.

Server Side Validation

To tackle this we had to dig into the code to find what hooks we can use for this. There were no documented actions or filters on the site that could help us directly with the validation. But then we found the following that did the job:

$this->form_data = apply_filters( 'ninja_forms_submit_data', $this->_form_data );

This filter allows you to access the submitted form data and modify it. We took the data from here, did the validation on our field ($field_id = 354) and added error to the $form_data[‘errors’][‘fields’][$field_id] variable:

add_filter( 'ninja_forms_submit_data', 'my_ninja_forms_submit_data');
function my_ninja_forms_submit_data( $form_data ) {
    
    $field_id = 354;

    // validation part
    $all_domains = get_option('fs_domain_list');
    $registration_email = $form_data['fields'][$field_id]['value'];
    $email_domain = explode("@",$registration_email);
    if (!(in_array($email_domain[1], $all_domains))) {
        // error message
        $form_data['errors']['fields'][$field_id] = 'This Email not allowed';
    }
    
    return $form_data;

}

 

I hope this will be useful for you and can save you some time searching.

2017-09-22T12:15:10+00:00 By |WordPress|