You are here

function units_mathematical_expression_element_validate in Units of Measurement 7.2

Validate function for 'units_mathematical_expression' form element.

1 string reference to 'units_mathematical_expression_element_validate'
units_element_info in ./units.module
Implements hook_element_info().

File

./units.module, line 859
Provide API for managing and converting units of measurement.

Code

function units_mathematical_expression_element_validate($element, &$form_state) {
  $mathematical_expression = NULL;
  try {
    $mathematical_expression = units_mathematical_expression_create_from_infix($element['infix']['#value']);

    // We evaluate the mathematical expression in order to make sure it contains
    // no dimensional contradictions.
    if (is_object($mathematical_expression)) {
      $mathematical_expression
        ->getExpression()
        ->evaluate();
    }
  } catch (UnitsMathematicalExpressionDimensionException $e) {
    form_error($element, t('%title mathematical expression contains error in dimensions.', array(
      '%title' => $element['#title'],
    )));
  } catch (UnitsMathematicalExpressionMalformedException $e) {
    form_error($element, t('%title contains malformed mathematical expression. @exception', array(
      '%title' => $element['#title'],
      '@exception' => $e
        ->getMessage(),
    )));
  }
  if (is_object($mathematical_expression) && $element['#allowed_dimension'] && !units_dimension_equal($element['#allowed_dimension'], $mathematical_expression
    ->getExpression()
    ->dimension())) {
    form_error($element, t('%title mismatches allowed dimension.', array(
      '%title' => $element['#title'],
    )));
  }
  if (is_object($mathematical_expression)) {
    switch ($element['#value_format']) {
      case 'object':
        break;
      case 'postfix':
        $mathematical_expression = $mathematical_expression
          ->getExpression()
          ->toPostfix();
        break;
      case 'infix':
        $mathematical_expression = $mathematical_expression
          ->getExpression()
          ->toInfix();
        break;
    }
  }
  form_set_value($element, $mathematical_expression, $form_state);
}