You are here

function format_number_numericfield_validate in Format Number API 6

Same name and namespace in other branches
  1. 7 format_number.module \format_number_numericfield_validate()

Validation of an individual numeric form element.

Parameters

$element: The form element being processed.

$form_state: A keyed array containing the current state of the form.

1 string reference to 'format_number_numericfield_validate'
format_number_numericfield_process in ./format_number.module
Process an individual numeric form element.

File

./format_number.module, line 505
This module provides a method to configure number formats (site default and user defined) with configurable decimal point and thousand separators. It also exposes several functions that can be used by other contributed or custom modules to display…

Code

function format_number_numericfield_validate($element, &$form_state) {
  $value = $element['#value'];
  if ($element['#required'] || $value != '') {
    $value = parse_formatted_number($value, $element['#required']);

    // Validate number format.
    if (!is_numeric($value)) {
      form_error($element, t('%name: The specified number @num is invalid.', array(
        '%name' => $element['#title'],
        '@num' => $element['#value'],
      )));
      return;
    }

    // Validate number boundaries.
    $element_precision = isset($element['#precision']) && (int) $element['#precision'] > 0 ? (int) $element['#precision'] : 12;
    $element_decimals = isset($element['#decimals']) && (int) $element['#decimals'] >= 0 ? (int) $element['#decimals'] : 0;
    $element_minimum = isset($element['#minimum']) ? parse_formatted_number($element['#minimum']) : NULL;
    if (!is_numeric($element_minimum)) {
      $element_minimum = format_number_compute_boundary('lower', $element_precision, $element_decimals);
    }
    $element_maximum = isset($element['#maximum']) ? parse_formatted_number($element['#maximum']) : NULL;
    if (!is_numeric($element_maximum)) {
      $element_maximum = format_number_compute_boundary('upper', $element_precision, $element_decimals);
    }
    if ($value < $element_minimum) {
      form_error($element, t('%name: The value may be no smaller than @minimum.', array(
        '%name' => $element['#title'],
        '@minimum' => $element_minimum,
      )));
      return;
    }
    elseif ($value > $element_maximum) {
      form_error($element, t('%name: The value may be no larger than @maximum.', array(
        '%name' => $element['#title'],
        '@maximum' => $element_maximum,
      )));
      return;
    }
  }

  // Update the form element with parsed number, so it gets a valid PHP number
  // that can be processed in math operations or store in the database.
  if ($element['#value'] != $value) {
    form_set_value($element, $value, $form_state);
  }
}