I generated a form by using the Webform module.
But how can I add validation for the elements in the form?

p.s
As forms_api.html said, I tried to add some validation code within the Advanced Settings/Additional Validation.
e.g.

    if ( !preg_match( '/^[a-zA-Z]+$/', $form_values['first_name']) ) {
      form_set_error('', t('The First Name you entered is not validated.'));
    }
}

or

    if ( !preg_match( '/^[a-zA-Z]+$/', $first_name) ) {
      form_set_error('', t('The First Name you entered is not validated.'));
    }
}

I wanted to validate the element called first_name, but both codes did not work!

Comments

mandclu’s picture

I've been able to do what you want by writing a module that implements hook_form_alter to set a new '#validate' value, and perform the additional validation there.

jaojao’s picture

How can i use the hook_form_alter function?
Could you write down the code within my case!

    if ( !preg_match( '/^[a-zA-Z]+$/', $form_values['first_name']) ) {
      form_set_error('', t('The First Name you entered is not validated.'));
    }
mandclu’s picture

OK, let's say the your form id is 'webform_client_form_2', you could create a module called myform:

function myform_form_alter($form_id, &$form) {
  if (strcmp('webform_client_form_2', $form_id) != 0) return;

  $form['#validate'] = array('myform_check_firstname' => array());
}

function myform_check_firstname($form_id, $form_values, $form) {
    if ( !preg_match( '/^[a-zA-Z]+$/', $form_values['first_name']) ) {
      form_set_error('', t('The First Name you entered is not valid.'));
    }
}
jaojao’s picture

Since I generated the form by Webform automatically, how can I know my form id? Is the form id indicative of form title?

mandclu’s picture

If you view the source (HTML) of the generated page, you should be able to get the form id.

jaojao’s picture

"Create a module called myform", you mean to create a new myform.module document and to save it under the direct.: drupal/modules/myform ?
If it said so, what should I do next? How to make the concatenation between my form and the module?

Alternatively, is there any simply way to write validating code just within the Advanced Settings/Additional Validation section? I really don't know how to deal with the Additional Validation section, even after read the API manual!!!!!

manuel garcia’s picture

OK, so after several hours researching this (note that I am not a programmer), I think I may be able to help here;

I was trying to validate that the user entered values in EITHER one of three fields in the form, here is my code:

<?php
if ($form_values['submitted_tree']['nombre']=='' && $form_values['submitted_tree']['cognoms']=='' && $form_values['submitted_tree']['nom_colectiu']==''){
	form_set_error('', t('Tiene que rellenar al menos uno de los siguientes campos: "Nom", "Cognoms" o "Nom del col·lectiu" para poder enviar el formulario.'));
}
?>

so basicaly it appears that in order to check the content of the field with field key "nombre", you have to call it by
$form_values['submitted_tree']['nombre']

So my guess is that for your issue, the code would look something like this:

<?php
    if ( !preg_match( '/^[a-zA-Z]+$/', $form_values['submitted_tree']['first_name']) ) {
      form_set_error('', t('The First Name you entered is not validated.'));
    }
}
?>

I haven't tested your code previously, so do let us know if it works for you now.

Also if someone could explain why the use of ['submitted_tree'] it would be nice to know :D

Greetings from Spain, and thanks for this great module!

jaojao’s picture

Thank you for your information!!!!!!!
It works eventually in my case. I understand now how the tree is constructed in the Webform. :)

if ( !preg_match( '/^[0-9]+$/', $form_values['submitted_tree']['fieldset_studium']['semester']) ) {
     form_set_error('', t('Fachsemester muss in nummer eingetragen werden!'));
     }

if ( !preg_match( '/^[0-9]+$/', $form_values['submitted_tree']['fieldset_kontakt']['zip']) ) {
     form_set_error('', t('ZIP muss in nummer eingetragen werden!'));
     }

p.s. there is a little trick when you write two validations parallelly. The 2. note, "ZIP muss in nummer eingetragen werden!", doesn't appear until the 1. validation is passed. It means, the validation is processed node by node. It confused me at the first time I tested the form! :)

And the "root" ['submitted_tree'] is still unknown. I suppose, it is defined by Webform in advance.

manuel garcia’s picture

I'm glad my input got you through the issue jaojao! :)

manuel garcia’s picture

Status: Active » Closed (fixed)

although it would be nice if someone documented this properly... :)

GBain22’s picture

Cheers guys, this has helped me so much. I have used this to help battle spam I was receiving through my webform. By adding in a question that the user had to type in to get right, then it processes the form. If anyone wants the code, just reply to me.

Thanks again, Garry.

devloper_sumi’s picture

Version: 5.x-1.x-dev » 6.x-2.1

Thanx for ur guidance...
Using this $form_values['submitted_tree']['confirm_email'] i bcame able to add additional validation

td540’s picture

Hi,
I'm looking for a way to send the user to a page node that acts as confirmation message, based on whether or not they gave the right answer in a specific field.

If they fill in the right answer, and they go to the "correct" node page.
If answer is wrong, go to the "wrong" node page.

roczei’s picture

Hi guys,

Here is a correct example for this issue, this is working in the validation field:

<?php

if ($form_state["values"]["submitted"]["16"] == '12500' && $form_state["values"]["submitted"]["17"] != '') {
  form_set_error('submitted][resztvev_adatai][szobatars_neve_ketagyas_szoba_eseten', "Error 1");
}

$nap_kivalasztva = 0;

foreach ($form_state["values"]["submitted"]["23"] as $k => $v) 
{ 
  if ($v != 0) $nap_kivalasztva = 1;
} 


if ($form_state["values"]["submitted"]["16"] == '0' && $nap_kivalasztva == 1){

form_set_error('submitted][resztvev_adatai][szallashelyen_toltott_ejszakak', "Error2");
}


if ($form_state["values"]["submitted"]["16"] != '0' && $nap_kivalasztva == 0){

form_set_error('submitted][resztvev_adatai][szallashelyen_toltott_ejszakak', "Errror3");
}


?>

My suggestion for debugging, IMPORTANT file: includes\form.inc

I changed it a bit.... :P


 793 function form_set_error($name = NULL, $message = '', $reset = FALSE) {
 794   static $form = array();
 795   if ($reset) {
 796     $form = array();
 797   }
 798   if (isset($name) && !isset($form[$name])) {
 799     $form[$name] = $message;
 800     if ($message) {
 801       drupal_set_message($message." ".$name, 'error');
 802     }
 803   }
 804   return $form;
 805 }

This was before:

801       drupal_set_message($message, 'error');

I changed it to this:

801       drupal_set_message($message." ".$name, 'error');

You can see that I added the ." ".$name thing, because it can be used for "form id" debugging.

Example for form id:

submitted][resztvev_adatai][szallashelyen_toltott_ejszakak

Why important to give the formid to form_set_error, because it will "add" color to the problematic field. Summary: use it. :)

Cheers,

Gabor

pavaniakella’s picture

Hi

Can any one post an blue print not the example.
So that I can write my names into it to change the code.

Cheers,
Pavani

vsalvans’s picture

Thanks a lot!

I tried dump variables by putting print_r into additional validation field but nothing appear.. I don't know how you figured out the name of the correct variable.

Moltes gràcies!

yan’s picture