You are here

function countries_admin_form_validate in Countries 7

Same name and namespace in other branches
  1. 8 countries.admin.inc \countries_admin_form_validate()
  2. 7.2 countries.admin.inc \countries_admin_form_validate()

Validate country form submissions.

File

./countries.admin.inc, line 217
Admin page callbacks for the Countries module.

Code

function countries_admin_form_validate($form, &$form_state) {

  // Edits
  $unique_keys = array(
    'name',
    'iso2',
    'iso3',
    'official_name',
    'numcode',
  );
  foreach ($unique_keys as $key) {
    if (drupal_strlen($form_state['values'][$key])) {
      $iso2 = isset($form['#country']) ? $form['#country']->iso2 : FALSE;
      if ($key == 'iso2' || $key == 'iso3') {
        $form_state['values'][$key] = drupal_strtoupper($form_state['values'][$key]);
      }
      else {
        $form_state['values'][$key] = trim($form_state['values'][$key]);
      }
      switch ($key) {
        case 'name':
          break;
        case 'iso2':
        case 'iso3':
          if (preg_match('/[^A-Z]/', $form_state['values'][$key])) {
            form_set_error($key, t('Please only use uppercase characters for ISO codes.'));
            continue;
          }
          else {
            $length = $key == 'iso2' ? 2 : 3;
            if (drupal_strlen($form_state['values'][$key]) != $length) {
              form_set_error($key, t('The ISO!length code must be exactly !length characters.', array(
                '!length' => $length,
              )));
              continue;
            }
          }
          break;
        case 'official_name':
          break;
        case 'numcode':
          if (preg_match('/[^0-9]/', $form_state['values'][$key])) {
            form_set_error($key, t('Only numbers are allowed for the number code.'));
            continue;
          }
          break;
      }
      if ($key == 'numcode' && empty($form_state['values'][$key])) {

        // Duplicate 0 values are OK.
      }
      elseif ((bool) db_query_range("SELECT 1 FROM {countries_country} WHERE iso2 <> :orginaliso2 AND LOWER({$key}) = LOWER(:{$key})", 0, 1, array(
        ':orginaliso2' => $iso2,
        ":{$key}" => $form_state['values'][$key],
      ))
        ->fetchField()) {
        form_set_error($key, t('The value %value is already taken.', array(
          '%value' => $form_state['values'][$key],
        )));
      }
    }
  }
}