CCK field element combined validation

This is how you can programmatically create a combined validation.

 

 

<?php
/**
* Create hook_form_alter and add a element validation function for your form and fields.
* In this case I want the selection in an option list to determine how to validate two other fields:
* If field_auto_client is 1,2,4 => field_default_group should be required
* If field_auto_client is 3     => field_default_client should be required
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  if (
$form_id == "backup_server_node_form") {

        if (isset(
$form['field_default_group'])) {
         
$form['field_default_group']['#element_validate'][] = 'mymodule_auto_client_validate';
        }
       
        if (isset(
$form['field_default_group'])) {
         
$form['field_default_client']['#element_validate'][] = 'mymodule_auto_client_validate';
        }

  }

}

/**
* If field_auto_client has the value 1,2 or 4 it has to have a value in field_default_group
* If field_default_client has the value of 3 it has to have a value in field_default_client
* Both field_default_group and field_default_client is valuated separately, so even if a bad
* value is given, they will be validated somewere else.
*
*
*/
function mymodule_auto_client_validate($element, &$form_state) {
   
$auto_client = $form_state['values']['field_auto_client'][0]['value'];
 
    if(
in_array($auto_client, array(1,2,4))) {

      if (
$element['#field_name'] == 'field_default_group') {
        if(empty(
$form_state['values']['field_default_group'][0]['nid'])) {
           
form_error($element, t('You have to select a Group to connect the Clients to. If needed you can !create_a_new_Group_here (opens in a new tab) and get back here and type in the Group name in the Default Group field below.', array('!create_a_new_Group_here' => l(t('create a new Group here'), "node/add/group", array('attributes' => array('target' => '_blank'))))));
        }
      }
    }

    if(
in_array($auto_client, array(3))) {

      if (
$element['#field_name'] == 'field_default_client') {
        if(empty(
$form_state['values']['field_default_client'][0]['nid'])) {
           
form_error($element, t('You have to select a Client to connect the Backup users to. If needed you can !create_a_new_Client_here (opens in a new tab) and get back here and type in the Client name in the Default Client field below.', array('!create_a_new_Client_here' => l(t('create a new Client here'), "node/add/client", array('attributes' => array('target' => '_blank'))))));
        }
      }
    }
}
?>
Knowledge keywords: