Previous: Drupal – Limit the number of values of a content type field by role @ 1
Another way to limit the number of values of content type field is adding an extra validation on the node create/edit form. Assume we have a content type called center and a media field called field_center_video.
1. Create a custom module and add an extra validation.
function <module>_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'center_node_form') {
// Add the extra validation
array_unshift($form['#validate'], 'addtional_validate');
}
}
function addtional_validate($form, $form_state) {
print_r($form_state);
form_set_error('field_center_video', 'test');
}
Now we could not save the form because of the validation and we could get a list of values stored in the $form_state. Since there are different kinds of CCK fields so you may need to use different checking for the limitation. In this example, the field_center_video stored in the $form_state is in the format
[values] => Array
(
...
[field_center_video] => Array
(
[0] => Array
(
=>
[value] =>
[_weight] => 0
)
[1] => Array
(
=>
[value] =>
[_weight] => 1
)
[field_center_video_add_more] => Add another item
)
...
My addition_validation should look like
function addtional_validate($form, $form_state) {
$count = 0;
foreach($form_state['values']['field_center_video'] as $video) {
if (!empty($video['value'])) {
$count++;
}
}
global $user;
// Only allow to upload 2 videos for role = staff
if (in_array('staff', $user->roles)) {
if ($count > 2) {
form_set_error('field_center_video', t('You cannot upload more than 2 videos'));
}
}
}
The approach should be better than then one we mentioned in Drupal – Limit the number of values of a content type field by role @ 1 because we could notify the user about the limitation using the form_set_error().
Done =)
Reference: Drupal – Add additional validation on Drupal form

This and your previous code do not work.
LikeLike
These 2 posts were about Drupal 6, are u using Drupal 7?
LikeLike
Is there any solution for drupal 7 ?
LikeLike
Have you tried the following solution? it should work for Drupal 7 too.
Drupal – Limit the number of values of a content type field by role @ 1
LikeLike