background image
HomeRecent PostsDrupalSearchTagsRSSContactAboutAccount

Adding custom validation to a CCK node type form

Eric.London's picture

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');
  }

}
?>

Another solution

Another solution would be to use MYMODULE_nodeapi()

function mkfj_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch($op) {
    //action=validate
    case 'validate':
      $form = $a3;
      switch($node->type) {
        //node type=MYTYPE
        case 'MYTYPE':
          if ( preg_match("BADWORDS", $form["field_name"][0]['value'] ) ) form_set_error("field_name", t("Message"));
          //...
        break;
      }
    break;
  }
}

Cheers,
Jan

D6 version

Great code, could you help me to release code for drupal 6 version ??
thanks before