How do I use Custom Serverside validation?

Serverside validation is important to help you validate the form data and to protect your site from malicious submissions. 

ChronoForms v4

A single validation

Here's an example using a Custom Serverside validation action to check a list of valid responses. The valid responses are included in an array, then a little PHP is used to check if the actual response is in the array:

1) Drag a Custom Serverside Validation action into the ON Submit event and move it up before any actions other than Anti-Spam checks.

2) Open it up and add code like this

<?php
$ok_values = array(
  'case1', 
  'case2',
  'case3'
);
if ( !in_array($form->data['data'], $ok_values) ) {
  $form->validation_errors['data'] = "Add message here";
  return false;
}
?>

3) Save and close the action then drag an Event Loop action into the pink On Fail event box (the default settings for the Event Loop are OK).

Using different PHP code you can apply almost any validation test here.


Running several validations

If you need to run more than one test, or test more than one input then this code is not good enough- it will fail at the first error and not find any errors in the following tests. You need to use a slightly different code structure to do this. Here's how it looks in 'pseudo-code':

<?php
if ( !test_1 ) {
  $form->validation_errors['input_1'] = "Add message 1 here";
}
if ( !test_2 ) {
  $form->validation_errors['input_2'] = "Add message 2 here";
}  
if ( !test_3 ) {
  $form->validation_errors['input_3'] = "Add message 3 here";
}
if ( isset($form->validation_errors) && count($form->validation_errors) > 0 ) {
  return false;
}
?>

With this code structure all the test will be run before the action Fails or Succeeds and all of the Error Messages will be displayed.


Upgrading validation code from CFv3

If you are upgrading forms from ChronoForms v3 or want to use some ServerSide validation code from the forums that was written for CFv3 there are two changes that you need to check for.

  1. You need to update the 'return' lines to use the CFv4 syntax above using separate messages and return false; to indicate an error.
  2. You need to check that any code using JRequest::get or still works correctly; it should do if there has been no processing before this action runs.

ChronoForms v5

ChronoForms v5 doesn't have a Custom Serverside validation action. There is a Server Validation action where you can add input names and custom error messages for the most common types of validation.

Note: array names like name[first_name] must be added in the form name.first_name:message

You can also use an Event Switcher action to add Custom Serverside validation where that is needed. However that does not offer the same methods to show errors.

Category: CFv4 Validation

Comments:

You need to login to be able to post a comment.