Custom Server-Side Validation

The Ninja Forms submission processes as an AJAX request, which expects a JSON object response from the server.

Custom validation errors can be set by manually terminating the request cycle, providing the errors as a JSON response.

Example

<?php
add_filter( 'ninja_forms_submit_data', function( $form_data ){
if( ! my_nf_validation( $form_data ) ) { // Add check here.
$errors = [
__( 'An unexpected error occurred.', 'my-plugin' )
];
$response = [
'errors' => $errors,
];
echo wp_json_encode( $response );
wp_die(); // this is required to terminate immediately and return a proper response
}
// If no errors, be sure to return the $form_data.
return $form_data;
});

Error Formatting

<?php
// Form Error
$errors[ 'form' ][ $error_id ] = 'Form Error';
// Field Error
$errors[ 'fields' ][ $field_id ] = 'Field Error';

view raw
error-format.php
hosted with ❤ by GitHub

Form Error Example

<?php
add_filter( 'ninja_forms_submit_data', function( $form_data ){
if( ! my_nf_validation( $form_data ) ) { // Add check here.
$errors = [
'form' => [
'my-error' => __( 'An unexpected error occurred.', 'my-plugin' ),
]
];
$response = [
'errors' => $errors,
];
echo wp_json_encode( $response );
wp_die(); // this is required to terminate immediately and return a proper response
}
// If no errors, be sure to return the $form_data.
return $form_data;
});

Field Error Example

Field validation on the server side is handled by the registered field class corresponding to each field type.

<?php
add_filter( 'ninja_forms_submit_data', function( $form_data ){
if( ! my_nf_validation( $form_data ) ) { // Add check here.
$errors = [
'fields' => [
'12' => __( 'An unexpected error occurred.', 'my-plugin' )
],
];
$response = [
'errors' => $errors,
];
echo wp_json_encode( $response );
wp_die(); // this is required to terminate immediately and return a proper response
}
// If no errors, be sure to return the $form_data.
return $form_data;
});