You are here

function fapi_validation_rules_execute in Form API Validation 7.2

Same name and namespace in other branches
  1. 6 fapi_validation.module \fapi_validation_rules_execute()
  2. 7 fapi_validation.module \fapi_validation_rules_execute()

Function for executing all rules

1 call to fapi_validation_rules_execute()
fapi_validate_element_validate in ./fapi_validation.module
Run element validation callbacks.

File

./fapi_validation.module, line 65

Code

function fapi_validation_rules_execute(&$element, &$form_state) {
  $data = _fapi_validation_data('rules');

  // If element is empty and not required, by pass rule validation
  if (!$element['#required'] && empty($element['#value'])) {
    return;
  }

  //establish errors array
  $errors = array();

  // Loop through all rules on the field
  foreach ($element['#rules'] as $rule) {
    $error_message = $error_callback = NULL;

    // If $rule is an array, use error message if is setted.
    if (is_array($rule)) {
      if (!isset($rule['rule'])) {
        drupal_set_message(t('Rule array with wrong structure on %field.', array(
          '%field' => $element['#name'],
        )), 'error');
        continue;
      }
      if (isset($rule['error'])) {
        $error_message = $rule['error'];
      }
      if (isset($rule['error callback'])) {
        $error_callback = $rule['error callback'];
      }
      $rule = $rule['rule'];
    }

    // Break rule into various aspects
    preg_match('/^(.*?)(\\[(.*)\\])?$/', $rule, $rs);
    $rule = $rs[1];

    // Check if rule exists
    if (!isset($data[$rule])) {
      drupal_set_message(t('Rule %rule not found!', array(
        '%rule' => $rule,
      )), 'error');
      continue;
    }

    //Get element value
    $params = array(
      $element['#value'],
    );

    // Parsing parameters from rule input
    if (isset($rs[3])) {
      if ($rule == 'regexp') {
        $params[] = array(
          $rs[3],
        );
      }
      else {
        $params[] = preg_split('/ *, */', $rs[3]);
      }
    }
    $params[] =& $element;
    $params[] =& $form_state;

    // Call the function for the associated role, with relevant params.
    $ret = call_user_func_array($data[$rule]['callback'], $params);

    // If it returns false (IE fails rule):
    if (!$ret) {
      if (!is_null($error_callback)) {
        $error_params = array(
          $rule,
          $params,
          $element,
          $form_state,
        );
        $errors[] = call_user_func_array($error_callback, $error_params);
      }
      else {
        $error = is_null($error_message) ? $data[$rule]['error_msg'] : $error_message;
        $errors[] = t($error, array(
          '%field' => $element['#title'],
        ));
      }
    }
  }
  if (!empty($errors)) {
    form_set_error(implode('][', $element['#parents']), implode('<br/>', $errors));
  }
}