You are here

function money_field_widget_validate in Money field 7

FAPI validation of an individual number element.

1 string reference to 'money_field_widget_validate'
money_field_widget_form in ./money.module
Implements hook_field_widget_form().

File

./money.module, line 505
This module defines the Money field.

Code

function money_field_widget_validate($element, &$form_state) {
  $instance = field_widget_instance($element, $form_state);
  $value = $element['amount']['#value'];

  // Dependency required by CurrencyLocalePattern class.
  ctools_include('export');
  $decimal_separator = CurrencyLocalePattern::loadFromEnv()->symbol_decimal_separator;

  // Reject invalid characters.
  if (!empty($value)) {
    $regexp = '@([^-0-9\\' . $decimal_separator . '])|(.-)@';
    $message = t('Only numbers and the decimal separator (@separator) allowed in %field.', array(
      '%field' => $instance['label'],
      '@separator' => $decimal_separator,
    ));
    if ($value != preg_replace($regexp, '', $value)) {
      form_error($element, $message);
    }
    else {

      // Verify that only one decimal separator exists in the field.
      if (substr_count($value, $decimal_separator) > 1) {
        $message = t('%field: There should only be one decimal separator (@separator).', array(
          '%field' => t($instance['label']),
          '@separator' => $decimal_separator,
        ));
        form_error($element, $message);
      }
      else {

        // Substitute the decimal separator; things should be fine.
        $value = strtr($value, $decimal_separator, '.');
      }
      form_set_value($element['amount'], $value, $form_state);
    }
  }
}