Validating CCK Form Fields

Custom validations with form error set on CCK may require custom coding. This is one such exercise for both Drupal 6 and Drupal 7.

Drupal 6

<?php
/**
* Validations for Employee Leave
*/

function custom_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if (
$op == 'validate' && $node->type == 'lms') {
   
$start_date =$node->field_lms_start_date[0]['value'];
   
$end_date =$node->field_lms_end_date[0]['value'];
    if(
$start_date > $end_date){
     
form_set_error('field_lms_start_date', 'Start Date of Leave Should be less than End Date of Leave');
    }
  }
}
?>

Drupal 7

<?php
function custom_form_alter(&$form, &$form_state, $form_id) {
   if(
$form_id == 'exam_node_form') {
    
$form['#validate'][] = 'custom_exam_node_form_validate';
   }
}

function
custom_exam_node_form_validate(&$form, &$form_state){
 
$exam_type = $form_state['values']['field_exam_assessment'][LANGUAGE_NONE][0]['tid'];
  if(
$exam_type == 45){  // External Assessment
     
form_set_error('field_exam_assessment',"Teaching Staff cannot create Assessment of type External. Please contact administrator");
  }
}
?>
Technologies: