Webform is very user-friendly - especially if you just need to create a form that sends an email. However, it doesn't have much out of the box validation built in. It will check that required fields are filled out, but that's it. Often, a user will want more validation than that. For example, a check to make sure that email address fields have valid email addresses entered.
Webform provides a place for additional validation in the 'Advanced Settings' section under 'Additional Validation.' Here's an example:
<?php
foreach ($form_values['submitted'] as $field_id => $value) {
$component = $node->webformcomponents[$field_id];
if (strpos($component['name'],"Email") !== FALSE && !valid_email_address($value)) {
form_set_error($field_id, t('Invalid Email Address.'));
}
elseif (strpos($component['name'],"Phone") !== FALSE && strstr($value,'X') !== FALSE) {
form_set_error($field_id, t('Invalid Phone Number.'));
}
elseif (strpos($component['name'],"List Name") !== FALSE && strstr($value,'xxx') !== FALSE) {
form_set_error($field_id, t('Invalid List Name.'));
}
}
?>
The $form_values array contains the values of all form fields within the current form. While iterating across the submitted values, this code checks to see if the name of the field contains a certain string. The name in this instance is not the contents of the HTML 'name' attribute. Instead, it is the name that you gave the field when creating it using the Webform module. For example, the first condition will check to see if the name of the field contains the word 'Email'. If it does, this validation script checks that the email is a valid one. If the email address is not valid, an error is thrown using the function form_set_error. The $field_id is the id of the form field throwing the error. This tells Webform to highlight that field in red.