Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 430
harpreet kaur Avatar asked Jul 22 '11 05:07

harpreet kaur


People also ask

How do I add a custom validation to a Webform element?

To add the new validation handler click on '+ Add Handler' as shown below. 2. A window should pop up with all the available custom handlers. There, select the custom handler 'Alter form to validate it' we just made and click on the 'Add handler' corresponding button.

How do I validate a custom form in Drupal 8?

To validate the form we just need to implement the validateForm() method from \Drupal\Core\Form\FormInterface in our HelloForm class. In our example we'll raise an error if the length of the title is less than 10 and also if the checkbox is not checked.

What is Webform module in Drupal?

The Webform module is a powerful and flexible Open Source form builder and submission manager for Drupal 8. The Webform module for Drupal provides all the features expected from an enterprise proprietary form builder combined with the flexibility and openness of Drupal.


1 Answers

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

like image 159
Allex Avatar answered Sep 23 '22 13:09

Allex