You are here

function fapi_validation_rules_execute in Form API Validation 7

Same name and namespace in other branches
  1. 6 fapi_validation.module \fapi_validation_rules_execute()
  2. 7.2 fapi_validation.module \fapi_validation_rules_execute()
1 call to fapi_validation_rules_execute()
fapi_validate_element_validate in ./fapi_validation.module
Run element validation callbacks.

File

./fapi_validation.module, line 57

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;
  }
  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'];
    }
    preg_match('/^(.*?)(\\[(.*)\\])?$/', $rule, $rs);
    $rule = $rs[1];
    if (!isset($data[$rule])) {
      drupal_set_message(t('Rule %rule not found!', array(
        '%rule' => $rule,
      )), 'error');
      continue;
    }
    $params = array(
      $element['#value'],
    );

    // Parsing parameters.
    if (isset($rs[3])) {
      if ($rule == 'regexp') {
        $params[] = array(
          $rs[3],
        );
      }
      else {
        $params[] = preg_split('/ *, */', $rs[3]);
      }
    }
    $params[] =& $element;
    $params[] =& $form_state;
    $ret = call_user_func_array($data[$rule]['callback'], $params);
    if (!$ret) {
      if (!is_null($error_callback)) {
        $error_params = array(
          $rule,
          $params,
          $element,
          $form_state,
        );
        $error = call_user_func_array($error_callback, $error_params);
      }
      else {
        $error = is_null($error_message) ? $data[$rule]['error_msg'] : $error_message;
        $error = t($error, array(
          '%field' => $element['#title'],
        ));
      }
      form_set_error($element['#name'], $error);
    }
  }
}