0

I'm using hook_form_alter() to add some custom validations. I have to check if a date field is empty or not; when the field is empty, I need to display an error message.

I don't know how to get the value from date field after a form is submitted and check it with empty().

I have tried the following lines, but none of them worked.

  • $form_state['input']['field_start_date']['und'][0]['value']
  • $form['field_start_date']['und'][0]['#default_value']['value']
  • $form_state['values']['field_start_date']

What am I doing wrong?

1 Answer 1

0

If the form contains a field_start_date form element, $form_state['values']['field_start_date'] is the only correct way to get the submitted values for that field.
Neither $form_state['input']['field_start_date']['und'][0]['value'] nor $form['field_start_date']['und'][0]['#default_value']['value'] is the correct way to fetch the submitted values.

Keep also in mind that, if you need to show a validation error when the value submitted for a form element is an empty value, probably you just need to set that form element as required. In that way, Drupal would require users enter a value and show a validation error to the users who don't enter a value. (Drupal would also show a red asterisk close to the form element, to let users know that form element is required.)
For this, it's enough to set #required to TRUE in hook_form_alter(). It doesn't require to write validation code, as that is done from Drupal core.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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