Drupal 5: Adding custom validation to a CCK node type form

Here is a quick code snippet that enables you to add your own custom validation to a CCK node type form.

<?php
function MYMODULE_form_alter($form_id, &$form) {
  // create a list of node types that require custom validation
  $nodeTypes = array(
    'MYNODETYPE1',
    'MYNODETYPE2',
  );

  // check if the form id is a node form, and if it exists in the above array
  if (substr($form_id,-10)=='_node_form' && in_array(substr($form_id, 0, strlen($form_id)-10), $nodeTypes)) {
    $form['#validate'] = array_merge(array('_MYMODULE_node_form_validate' => array()), $form['#validate']);
  }
}

function _MYMODULE_node_form_validate($form_id, $form_values, $form)
{
  // DEBUG: use print_r($form_values) to see what has been submitted
  // TODO: check for errors here, and use form_set_error() as necessary

  // for example:
  if ($form_values['MYFIELD'][0]['value'] == 'SOMETHING NAUGHTY') {
    form_set_error('MYFIELD', 'MY CUSTOM ERROR MESSAGE');
  }

}
?>

Updated: