This is a collection of PHP snippets that you can use to add custom validation to your Webforms. In any validation script, you may use the Drupal function
form_set_error() to prevent the form from submitting and display a message to the user. It is also important to note that in Webform, you cannot change the $form_values or $form_state variables that are available to you in the additional validation code (you can, but it won't be saved). If needing to change these values, change them in the Additional Submission code instead.
This snippets are only intended for use with the Webform 2.x module. They will not work with CCK or other modules. For information on additional PHP processing in Webform 3.x, see http://drupal.org/node/754580 and http://drupal.org/project/webform_php.
To use any of these snippets:
- Visit the permissions page (admin/user/access in D5 or admin/user/permissions in D6) and ensure the current user has the "use PHP for additional processing" permission.
- Create or edit a new Webform
- Under the "Webform advanced settings", enter the snippet, including the
The code will need to be updated slightly to work with your form. Wherever you see a field key, such as
$form_values['submitted']['name_of_field'] you'll need to update the name of the field with the field key from your form. This field key is automatically assigned to fields (usually an all lowercase, no spaces version of the field label), but you can edit the key manually by editing an individual field and in the field configuration form change the Field Key value in the Advanced fieldset.
Please note that the examples assume you are not using fieldsets to group your fields in the form. If this is not the case, you must change you code accordingly, using for example
form_set_error('submitted][name_of_fieldset][name_of_field', t('Error message.'));
Webform validation module (D6)
If you don't wish to add custom validation code to your webform directly or are looking for a better user interface to validate your webform components, check out the Webform Validation module.
This module comes with a set of default validation rules you can apply to your webform components, as well as the option to define your own validation rules in a custom module through the module's hooks.
See the Advanced webform validation with Webform Validation module handbook page for more information