表单的自定义验证?


30

我需要向表单添加自定义验证,让我们说添加文章表单。

我原本希望hook_FORM_ID_validate()可以处理此类问题,但是在API文档中找不到任何相关内容。

向表单添加自定义验证的方法是什么?

Answers:


57

您可以按以下方式将任意数量的验证功能添加到任何形式hook_form_FORM_ID_alter()

function mymodule_form_article_node_form_alter(&$form, &$form_state, $form_id) {
  // There will already be some validate handlers added so you need to add to the
  // array rather than overwrite it.
  $form['#validate'][] = 'mymodule_article_form_validate';

  // As mentioned above you can add as many as you want
  $form['#validate'][] = 'mymodule_article_form_validate_2';
}

function mymodule_article_form_validate($form, &$form_state) {
  // Random example, if the title is 'test' throw an error
  if ($form_state['values']['title'] == 'test') {
    form_set_error('title', 'Title cannot be "test"');
  }
}

假设我已经将自定义表单验证添加到已经具有2个验证功能的表单中。那么在drupal 7中哪个是首选?
大师

@Guru
Clive中

如果表单是user_registration_form,则它始终保留“ [#validate] =>数组([0] => user_account_form_validate [1] => user_validate_picture”)。假设我要添加自定义验证。然后应该是这样的:[[#validate] => Array([0] => user_account_form_validate [1] => user_validate_picture [2] => user_register_validate)”。但我想首先运行“ user_register_validate”功能。
大师

对于其他领域,您必须使用:if ($form_state['values']['field_custom']['und'][0]['value'] == 'Error') { //throw error }
克里斯·

如何以这种方式设置大小,扩展名的验证?还有一个问题,是否有ajax功能,例如“上载”和“删除”,我们如何处理此验证?
steniya

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.