How do I apply webform validation in drupal 7?

harpreet kaur picture harpreet kaur · Jul 22, 2011 · Viewed 12.6k times · Source

I have webforms in my drupal 7 website. What I want is to validate my webform fields. The webform contains a phone field which should accept numeric field and should contain 10 numbers only. Is there any module for this or will I have to code for this.

Answer

Allex picture Allex · Jul 22, 2011

Use hook_form_alter() to apply custom validation in drupal

create module e.g. mymodule

file mymodule.module

function mymodule_form_alter(&$form, &$form_state, $form_id)
{
    print $form_id;

    if($form_id=='webform_client_form_1') //Change webform id according to you webformid
    {
        $form['#validate'][]='mymodule_form_validate';
        return $form;
    }
}

function mymodule_form_validate($form,&$form_state)
{
    //where "phone" is field name of webform phone field
    $phoneval = $form_state['values']['submitted']['phone'];

    if($phoneval=='')
    {
        form_set_error('phone','Please fill the form field');
    }
    // Then use regular expression to validate it.
    // In above example i have check if phonefield is empty or not.
}

If you want to more to detail how to use hook_form_alter() visit this link http://www.codeinsects.com/drupal-hook-system-part-2.html