Search code examples
formsvalidationdrupal

How to use form validation in Drupal 7


I am trying to edit the checkout form in Drupal Commerce, to require a user to enter their email address twice. When they submit their form, Drupal should check to see if the emails match, and call form_set_error() if they don't. For now, I am just trying to attach a custom validation function to the form, which I can't get to work. (My module is called checkout_confirm_email. This module is only for our own use, so I didn't put much effort into the name).

function checkout_confirm_email_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'commerce_checkout_form_checkout') {
    $form['#validate'][] = 'checkout_confirm_email_form_validate';
    dprint_r($form['#validate']);
    dsm("I printed");
}
}

function checkout_confirm_email_form_validate($form, &$form_state) {    
    dsm("Never prints...");
}

The dprint_r statment outputs Array ([0] => checkout_confirm_email_form_validate). So the function is part of the form array, but the dsm statement in the validation function never prints.

I've actually been stuck for a while. I've looked up examples, and I can't see what I'm doing wrong. Anyone?


Solution

  • You need to attach the #validate property to the form submit button like this:

    $form['submit']['#validate'][] = 'checkout_confirm_email_form_validate'
    

    And it'll work then it's not necessary that my example is identical match to your form tree you should search for the submit button array and apply this example to it