Search code examples
validationdrupal-7drupal-webform

How do I apply webform validation in drupal 7?


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.


Solution

  • 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