In D6, the method I used was to store the value of form fields into a variable and then setting an error message of the variable == null.

Is this still possible in D7, or is there a better way to handle this? The fields I'm trying to apply custom validation to are select lists so I imagine there must be a different technique.


I figured it out on my own: The process is the same as in Drupal 6. The arrays have just changed a bit. To use a custom validation with hook_form_alter() and a custom validation function, you would load your form_state values as follows (example based on fields from profile2):

function example_validate($form, &$form_state) {
  // Store our field values to validate against.
  $fieldname = $form_state['values']['profile']['field_name']['und'][0]['value'];

  if ($fieldname == null) {
    form_set_error('profile][field_name', t('Error Message'));

The actual value for our fields is now found in the 'und' array. Since the #parent property of these profile fields is an array, use 'foo][foo2' format to specify the element for which to show the validation error. See form_set_error().

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.