Custom Validation

Sometimes you will want to custom process your form, enter it into a database or just do something other than send and email and redirect to a thank you page. You can essentially do anything you like by testing $o_form->isSubmitted() along with $o_form->getInvalidElements().

You can find the snippet code in the file core/components/jsonformbuilder/docs/examples/JsonFormBuilder-customvalidationcheck.php.

The Code

<?php
require_once $modx->getOption('core_path',null,MODX_CORE_PATH).'components/jsonformbuilder/model/jsonformbuilder/JsonFormBuilder.class.php';

//CREATE FORM ELEMENTS
$o_fe_name      = new JsonFormBuilder_elementText('name_full','Your Name');
$o_fe_email     = new JsonFormBuilder_elementText('email_address','Email Address');
$o_fe_buttSubmit    = new JsonFormBuilder_elementButton('submit','Submit Form','submit');
  
//SET VALIDATION RULES
$a_formRules=array();
//Set required fields
$a_formFields_required = array($o_fe_name, $o_fe_email);
foreach($a_formFields_required as $field){
    $a_formRules[] = new FormRule(FormRuleType::required,$field);
}
$a_formRules[] = new FormRule(FormRuleType::email, $o_fe_email, NULL, 'Please provide a valid email address');
  
//CREATE FORM AND SETUP
$o_form = new JsonFormBuilder($modx,'contactForm');
$o_form->addRules($a_formRules);
$o_form->setJqueryValidation(true);
$o_form->setPlaceholderJavascript('JsonFormBuilder_myForm');
  
//ADD ELEMENTS TO THE FORM IN PREFERRED ORDER
$o_form->addElements(
    array(
        $o_fe_name,$o_fe_email,$o_fe_buttSubmit
    )
);

//You must validate the form here before you can check if isSubmitted or check the invalid elements count as shown below.
$o_form->validate();
if($o_form->isSubmitted()===true && count($o_form->getInvalidElements())===0){
    //form was submitted and is valid. Now we can do what we want and redirect elsewhere manually.
    
    $b_oktoSubmit = true;
    //Can also add in your own custom error messages and re-validate.
    if($b_oktoSubmit===false){
        $o_form->addError($o_fe_name,'Sorry, there is a custom error here.');
        $o_form->validate();
        $b_okToProceed=false;
        return $o_form->output();
    }else{
        echo 'Form was submitted and was valid. Do things here :)';
        exit();
    }
}else{
    //otherwise run the form as normal (which will display the errors).
    return $o_form->output();
}

Breaking it Down

A simple test to check that the form is firstly submitted, and has no validation errors is done in the last few lines of the example above.

$o_form->isSubmitted() will return a boolean true if the form has been submitted, and the $o_form->getInvalidElements() will return an array of invalid form element objects. If this is empty and the form is submitted, we can assume we are fine to go ahead and process the data and redirect to wherever.