验证Drupal表单中的输入

时间:2011-07-20 16:03:35

标签: php drupal-6 drupal-forms

我有一个Drupal表单,其中有人输入信息,我需要进行数据库查询以在提交之前检查它是否有效。我想要一个按钮,用户可以单击以检查有效性(或者在用户离开该字段后自动完成),然后显示有关其选择的一些信息。
我知道我可以使用hook_form_submit在提交表单时查看表单,然后在出现任何错误时停止该进程,但我希望用户能够在提交表单之前确认他们选择了正确的表单。

2 个答案:

答案 0 :(得分:2)

我没有亲自尝试过这个模块,但它可能正是你想要的:

http://drupal.org/project/ajax

如果您只是在寻找实时查找的方法(例如输入图书条形码和获取标题),您还可以使用Drupal的自动完成功能,但它需要您编写自己的自动完成功能处理数据库查找。

答案 1 :(得分:0)

看看:Basic form with validate handler。你真的只需要添加一个类似于mymodule_myform_validate($form, &$form_state) { ... }的函数。从链接页面:

“这会添加一个新的表单字段以及使用validate函数验证它的方法,也称为验证处理程序。”

<?php
function my_module_menu() {
  $items = array();
  $items['my_module/form'] = array(
    'title' => t('My form'),
    'page callback' => 'my_module_form',
    'access arguments' => array('access content'),
    'description' => t('My form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function my_module_form() {
  return drupal_get_form('my_module_my_form');
}

function my_module_my_form($form_state) {
  $form['name'] = array(
    '#type' => 'fieldset',
    '#title' => t('Name'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['name']['first'] = array(
    '#type' => 'textfield',
    '#title' => t('First name'),
    '#required' => TRUE,
    '#default_value' => "First name",
    '#description' => "Please enter your first name.",
    '#size' => 20,
    '#maxlength' => 20,
  );
  $form['name']['last'] = array(
    '#type' => 'textfield',
    '#title' => t('Last name'),
    '#required' => TRUE,
  );

  // New form field added to permit entry of year of birth.
  // The data entered into this field will be validated with
  // the default validation function.
  $form['year_of_birth'] = array(
    '#type' => 'textfield',
    '#title' => "Year of birth",
    '#description' => 'Format is "YYYY"',
  ); 

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  return $form;
}

// This adds a handler/function to validate the data entered into the 
// "year of birth" field to make sure it's between the values of 1900 
// and 2000. If not, it displays an error. The value report is // $form_state['values'] (see http&#58;//drupal.org/node/144132#form-state).
//
// Notice the name of the function. It is simply the name of the form 
// followed by '_validate'. This is the default validation function.
function my_module_my_form_validate($form, &$form_state) {
  $year_of_birth = $form_state['values']['year_of_birth'];
  if ($year_of_birth && ($year_of_birth < 1900 || $year_of_birth > 2000)) {
    form_set_error('year_of_birth', 'Enter a year between 1900 and 2000.');
  }
}
?>
相关问题