04. Validate the form submission

Last modified: May 26, 2009 - 01:42

If you have downloaded, installed, enabled, and set permissions for a user to add a todo item, then said user can view the todo add page via the node/add/todo URL. If you have other modules and permissions set for this user, your user will also see the other form fields. These might include input formats, file attachments, comment settings, menu or path settings, publishing options and authoring information.

We'll adjust these later in the form editing process, removing what we don't need. For now, we want to validate the data when the user submits the form. The validation we'll use will be somewhat artificial, but will demonstrate the process.

Forms will automatically validate for invalid choices for a select element, so we don't need to check the priority or status values.

Eventually, we'll want to use a javascript calendar to make date selection easier for the user. In anticipation of using this widget, we'll use the javascript calendar's date input format for our form. The format the javascript calendar uses is somewhat configurable, so it can later be updated to match the date format desired.

Note that this example is using the Form API validate hook and not the Node API validate hook.

<?php
/**
* Validate our forms
* @param string form id
* @param array form values
*/
function todo_validate($form_id, $form_values) {

   
// if the user specified a date, validate the format
   
if (isset($form_values['duedate']) && (trim($form_values['duedate']['#value']) != '')) {
       
       
// check the date format
       
if (!preg_match('/^(\d\d)\/(\d\d)\/(\d\d\d\d)$/', $form_values['duedate']['#value'], $matches)) {
           
form_set_error('duedate', t('Due date should be in the format dd/mm/yyyy'));
        } else {

           
// make sure the date provided is a valid date
           
if (!checkdate($matches[2], $matches[1], $matches[3])) {
               
form_set_error('duedate', t('Please enter a valid date'));
            }
           
        }
    }
}
?>

This validation checks the due date is of the format ##/##/####, and that the date entered is a valid one. For example, 49/13/2001 is an invalid date, but 28/02/2001 is valid.

If you need to validate other fields, access the form value via $form_values[fieldname]['#value']. To see other values available,

An easy way to view all the values in the form array is to print them out and look at all of them on submit, using the print_r function:

<?php
// dump the form validate variables
function todo_validate($form_id, $form_values) {
  print
'<pre>'. print_r($form_values, true) .'</pre>';
  exit();
}
?>

Download the module thus far, and rename to todo.module before saving in your Drupal installation.

 
 

Drupal is a registered trademark of Dries Buytaert.