Drupal 7 validate node before save

Categories: 

Tags: 

Objective

Make whatever we want before validate and submit a node.

hook_node_validate

/**
 * hook_node_validate
 */
function my_module_node_validate($node, $form, &$form_state)
{
    if ($node->type == 'article') {
        // Check whatever condition with the node content
        if (!isset($node->body)) {
            form_set_error('body', t('Body can\'t be empty'));
        }
    }
}

hook_node_submit

/**
 * Hook node_submit
 */
function my_module_node_submit($node, $form, &$form_state)
{
    global $base_url;
 
    if ($form['#form_id'] == 'my_content_type_node_form') {
        // Do whatever before save
 
        // ...
 
        // Save node
        node_save($node);
 
        // Set message
        drupal_set_message(t('Content has been submitted correctly.'));
 
        // Redirect
        drupal_goto($base_url . '/my_custom_page');
    }
}