Creating A Custom Validation Processor For Caldera Forms

Caldera Forms Banner

When you have a form with unique needs, such as one that powers a registration systems, you may need to create a custom validation for a specific field. For example, if you need to check if a field value matches a list of allowed values. Or you may need to see if a field’s is in a certain range. Another use for this type of processor is for adding invite code functionality to your event registration form, or user registration form created with the Caldera Forms Users add-on.

While adding validation in the browser using conditional logic or custom JavaScript may provide for a good user experience, often server-side database lookups or other PHP code is necessary for ensuring the correct validation.

This tutorial shows how to make a simple Caldera Forms processor to validate the value of a field. Caldera Forms processors can act at any, or all of these three stages of form submission processing:

  • Pre-process: Used for any process that is required to be successful for the submission to be complete. This is the most commonly stage.
  • Process: Runs after pending entry is created. Not commonly used, but provides an opportunity to return errors, after all pre-processing is complete.
  • Post-process: Runs before final entry saving is performed and emails are sent. Useful for modifying field values, or adding extra meta data to entry.

Creating The Processor

All of the code for this tutorial can be found in a Git repository. Feel GPL free to fork that repository as the basis for your own Caldera Forms processor.

If you are creating this plugin from scratch, start by creating a new directory in your site’s plugins directory. Name that directory a useful name to describe what this processor plugin will do. In that directory create two files. Name the first file first file for the plugin’s name and add have a valid plugin header. The second file will be for the processor’s settings UI. Call this file config.php or something else meaningful.

In the main plugin file, we need to use the “caldera_forms_get_form_processors” filter to declare this processor’s configuration. Here is how that looks:

add_filter('caldera_forms_get_form_processors', 'my_custom_cf_validator_processor');

/**
 * Add a custom processor for field validation
 *
 * @uses 'my_custom_cf_validator_processor'
 *
 * @param array $processors Processor configs
 *
 * @return array
 */
function my_custom_cf_validator_processor($processors){
    $processors['my_custom_cf_validator'] = array(
        'name' => __('Custom Validator', 'my-text-domain' ),
        'description' => '',
        'pre_processor' => 'my_custom_validator',
        'template' => dirname(__FILE__) . '/config.php'

    );

    return $processors;
}

As with all examples in this tutorial, you should change the prefix for functions from “my_custom” to a unique prefix for your plugin.

Because we are making a validation processor, this processor will only act at the pre-processor stage described above. This will allow us to check a field value, and if it is not valid return errors. We could add arguments to our processor configuration array for “processor” to run a function at the processor stage, or “process” to run a function at the process stage.

 

Creating The Processor UI

Caldera Forms provides a utility class Caldera_Forms_Processor_UI for generating processor configuration interfaces in the correct manner. While using this class is not technically required, it is highly recommended. Using this class is super easy, and ensures that your processor UI will display and save properly. It also helps ensure that any future changes in the Caldera Forms admin system will not affect your processor’s UI.

Using this class requires an array of field definitions. Create a function in your main plugin file for this. We will need this same array later when running the processor, so having a function that we can use twice is important.

/**
 * Processor fields
 * 
 * @return array
 */
function my_custom_cf_validator_fields(){
    return array(
        array(
            'id' => 'field-to-validate',
            'type' => 'text',
            'required' => true,
            'magic' => true,
            'label' => __( 'Magic tag for field to validate.', 'my-text-domain' )
        ),
    );
}

This just adds one field “field-to-validate”, but you could add more fields if you needed to. Note that we are setting the argument “magic” to true, which enables the magic tag binding button and auto-complete.

Now, in the config.php file of the processor plugin, we just need to add one line to create the processor UI:

echo Caldera_Forms_Processor_UI::config_fields( my_custom_cf_validator_fields() );

Feel free to add additional HTML or even inline JavaScript here.

Creating The Validator

Now we are going to add the pre_process callback function that will preform the validation. I like to have a separate function that does the actual check if the value is valid, that way, if needed I can reuse that function elsewhere. Here is the simple validator function I created:

function my_custom_cf_validator_is_valid( $value ){
    return in_array( $value, array(
        'Han Solo',
        'Chewbacca',
        'Rey'
    ) );
}

This function is probably not useful to you. It just checks if a value is one of three names. You should modify this function to fit your needs. You might be able to use a hardcoded array here, or you may do a database lookup.

Now that we have a way to perform the validation, we can create our pre_processor callback that uses it. This processor will use the Caldera_Forms_Processor_Get_Data class to extract important information, such as the value we are validating. If validation fails, it will be even more useful.  Here is the pre_processor callback:

/**
 * Run field validation
 *
 * @param array $config Processor config
 * @param array $form Form config
 *
 * @return array|void Error array if needed, else void.
 */
function my_custom_validator( array $config, array $form ){

    //Processor data object
    $data = new Caldera_Forms_Processor_Get_Data( $config, $form, my_custom_cf_validator_fields() );

    //Value of field to be validated
    $value = $data->get_value( 'field-to-validate' );

    //if not valid, return an error
    if( false == my_custom_cf_validator_is_valid( $value ) ){

        //get ID of field to put error on
        $fields = $data->get_fields();
        $field_id = $fields[ 'field-to-validate' ][ 'config_field' ];

        //Get label of field to use in error message above form
        $field = $form[ 'fields' ][ $field_id ];
        $label = $field[ 'label' ];

        //this is error data to send back
        return array(
            'type' => 'error',
            //this message will be shown above form
            'note' => sprintf( 'Please Correct %s', $label ),
            //Add error messages for any form field
            'fields' => array(
                //This error message will be shown below the field that we are validating
                $field_id => __( 'This field is invalid', 'text-domain' )
            )
        );
    }

    //If everything is good, don't return anything!

}

This function gets the value of the field being validated and checks if it is valid. If it is valid this function will not return anything. Pre-processors should only return values if an error has occurred. Returning anything at the pre-process state will stop form submission.

If the validation fails, we return an array that will cause an error to be displayed over the form and additional error message to show under the field that has failed validation. This array has the following keys:

  • Type: This should be “error”, which will cause the notice to use the alert class.
  • Note: This is the message that goes above the form.
  • Fields: This is an array of field IDs that will get additional verification errors printed. You can add as many field IDs here as you need.

That’s It! Make It Your Own

That’s all you need. Remember, all of this code is on Github. With a few changes that plugin could be all you need to add a custom validation processor add-on for your site. It could even be the basis for a cool add-on plugin.