Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
I'm using a validation rule to ensure that the user enter distinct values in a specific components list.
I copy my code, maybe it will be useful to someone or could be incorporated into the module.
/**
* Implements hook_webform_validation_validators().
*/
function YOURMODULE_webform_validation_validators() {
return array(
'distinctvalues' => array(
'name' => t('Distinct values'),
'component_types' => array(
'number',
'textfield',
'email',
'select',
'hidden',
),
'min_components' => 2,
'description' => t('Verifies that all specified components contain distinct values.'),
),
);
}
/**
* Implements hook_webform_validation_validate().
*/
function YOURMODULE_webform_validation_validate($validator_name, $items, $components, $rule) {
if ($items) {
switch ($validator_name) {
case 'distinctvalues':
$values_count = array_count_values($items);
foreach ($values_count as $key => $val) {
if (!empty($key) && $val > 1) {
$errors[] = t('You have selected %count times the value %value. You cannot repeat values.', array('%count' => $val, '%value' => $key));
}
}
return $errors;
break;
}
}
}
Comments
Comment #1
oriol_e9gComment #2
Liam MorlandIs this not the same as the unique validator?
Comment #3
oriol_e9gThe "unique validator" validates that the value doesn't match with the values of other users, for example an ID or email. The distinct validator ensures that the user don't repeat values in his form, don't compare with other users values. For exemple:
Which Is your favorite fruit? Order from 1 to 3
- Apple: 3
- Strawberry: 1
- Banana: 2
distinctvalues: OK
- Apple: 2
- Strawberry: 1
- Banana: 2
distinctvalues: Error. 'You have selected 2 times the value '2'. You cannot repeat values.
This validator is useful for forms that uses preferential sistem voting like Borda Count (http://en.wikipedia.org/wiki/Borda_count), IRV (http://en.wikipedia.org/wiki/Instant-runoff_voting) or similars.
Comment #4
Liam MorlandThe unique validation in Webform checks for uniqueness between users. The unique validator in Webform Validation checks multiple components in the same submission. Here is the description:
Comment #5
Liam MorlandIf this does not do what you want, please re-open and provide details.