I need to validate my form and return a specific error message if the terms of agreement checkbox isn't checked (it's a required field). So I've placed the following code in my CommerceAlter.module. However, it's not working (ie. the error text is still showing the default error text):

function CommerceAlter_form_validate(&$form, &$form_state, $form_id) {
  if (form_get_errors()) {
    $form_errors = form_get_errors();
    $drupal_errors = drupal_get_messages('error');

    // Clear form errors

    foreach($drupal_errors['error'] as $key => $error) {
        if (in_array($error, $form_errors)) {
            // Unset form errors

    // Rebuild drupal errors
    foreach($drupal_errors['error'] as $key => $message) {
        drupal_set_message($message, 'error');

    // Validate form field and set error message    
    if ( $form_state['values']['customer_profile_billing']
['field_i_have_read_and_i_agree_to']['und']['0']['value'] === 0 ) {

            form_set_error('value', t('You forgot to check the required 
checkbox. Please try again.'));

Any idea what I might be doing wrong here?

1 Answer 1


I guess you can obtain the field value using this.

if ( $form_state['values']['field_i_have_read_and_i_agree_to'] == 0 ) {
  //or use this in if statement $form_state['values']['customer_profile_billing']['field_i_have_read_and_i_agree_to']

      form_set_error('field_i_have_read_and_i_agree_to', t('You forgot to check the required checkbox.Please try again.'));

You shouldn't include ['customer_profile_billing'] unless you have set the #tree to TRUE.

  • hmmm...I'm basing the whole field name off what's available in dpm($form_state) and that's showing the value as being in the following array: values > customer_profile_billing > field_i_have_read_and_i_agree_to > und > 0 >value 0. I guess I don't understand your #tree comment. I tried what you gave me and it still doesn't work.
    – Sage
    Sep 24, 2015 at 0:50

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.