background image
HomeRecent PostsDrupalSearchTagsRSSContactAboutAccount
Eric.London's picture

At some point you might want add validation to the user edit form to ensure username is a valid email address. You can accomplish this by adding a form_alter hook, testing for the user profile form, and adding a validation handler to the $form object.

<?php
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
 
// test for the user profile edit form
 
if ($form_id == 'user_profile_form') {
   
// add another validation function to the list
   
$form['#validate'][] = '_MYMODULE_form_alter_user_profile_validate';
  }
}

// define the validation function
function _MYMODULE_form_alter_user_profile_validate($form, &$form_state) {
 
// validate the username and set a form error as necessary
 
if (!valid_email_address($form_state['values']['name']))
   
form_set_error('name', 'Username must be a valid email address.');
}
?>

Eric.London's picture

Here's a code snippet that ensures the submitted title is unique across all nodes.

<?php
function MYMODULE_form_alter($form_id, $form) {
  if (
substr($form_id, -10)=='_node_form') {
   
// add custom form validation function
   
$form['#validate'] = array_merge(array('_MYMODULE_helper_validate' => array()), $form['#validate']);
  }
}

function
_MYMODULE_helper_validate($form_id, $form_values, $form) {
 
// ensure title is unique
 
if (strlen($form_values['title'])) {
   
// check for unique title
   
$sql = "select distinct title from {node} where 1=1 ";
   
// don't want to include current title
   
if ($form_values['nid']) $sql .= "and nid != '" . db_escape_string($form_values['nid']) . "'";
       
   
$resource = db_query($sql);
   
$titles = array();
    while(
$result = db_fetch_array($resource)) $titles[] = $result['title'];
   
    if (
in_array($form_values['title'],$titles))
     
form_set_error('title', $form['title']['#title'] . ' has already been submitted.');
  }
}
?>

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

}
?>

Syndicate content