Madhu Nair
Madhu Nair

Reputation: 436

Field validation to compare two field values

I've created a content type using two fields "capacity" and "count".

In a custom module I'd like to validate that field "count" should be less than field "capacity".

function MYMODULE_node_form_validate($form, &$form_state) {

  $capacity = $form['capacity']['#value'];
  $count = $form['count']['#value'];

  if ($count > $capacity) {
    form_set_error('title', 'Not possible');
  }
}

Upvotes: 2

Views: 620

Answers (1)

norman.lol
norman.lol

Reputation: 5374

First add a custom validation function, then fire your logic from there and prevent the form from further processing if necessary. Replace MYMODULE and MYCONTENTTYPE with your machine names.

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MYMODULE_form_node_form_alter(&$form, &$form_state, $form_id) {

  // Find the content type of the node we are editing.
  $content_type = $form['#node']->type;

  if ($content_type == 'MYCONTENTTYPE') {

    // Add an additional custom validation callback.
    $form['#validate'][] = 'MYCUSTOM_FORMVALIDATION';
  }
}

/**
 * Custom MYCONTENTYTPE node form validation.
 */
function MYCUSTOM_FORMVALIDATION($form, &$form_state) {

  // Better check isset() and !empty() first. Depends on your needs.
  // Convert values to comparable numbers.
  // Maybe you prefer intval() or some other logic. Depends on your needs.
  $field_a = floatval($form_state['values']['field_a'][LANGUAGE_NONE][0]['value']);
  $field_b = floatval($form_state['values']['field_b'][LANGUAGE_NONE][0]['value']);

  // Stop the form from further processing if field A < than field B.
  if ($field_a < $field_b) {
    form_set_error('stop', t('Field A shall be greater then Field B'));
  }
}

Upvotes: 3

Related Questions