Thursday, May 26, 2011

Few ways to validate drupal node and node form

Few ways to validate drupal node and node form

Method 1: drupal form
<?php
function moduleName_sample_form($form_state) {
  $form['comp_name'] = array(
    '#type' => 'textfield',
    '#title' => 'Company Name',
  );
}

function moduleName_sample_form_validate($form, &$form_state) {
  if (strlen($form_state['values']['comp_name']) < 3)) {
    form_set_error('comp_name', 'company name must be more than two characters.');
  }
}
?>

Method 2: hook_nodeapi()
<?php
/**
 * Implementation of hook_nodeapi().
 */
function moduleName_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op === 'validate') {
    if (empty($node->field_start_date[0]['value'])) {
      form_set_error('field_start_date', 'Start Date must not be empty.');
    }
  }
}
?>

Method 3: hook_form_alter()
<?php
/**
 * Implementation of hook_form_alter().
 */
function moduleName_form_alter(&$form, $form_state, $form_id) {
  if ($form_id === 'contact_node_form') {
    moduleName_reset_contact_node_form_fields($form);
  }
}

function moduleName_reset_contact_node_form_fields(&$form) {
  ### validate start date and end date.
  $form['#validate'][] = 'moduleName_validate_field_start_end_date';
}

function moduleName_validate_field_start_end_date($form, &$form_state) {
  if (empty($form_state['values']['field_start_date'][0]['value'])) {
    form_set_error('field_start_date', 'Start Date must not be empty.');
  }
}
?>

No comments: