douba2011 2018-03-27 07:52
浏览 23
已采纳

用于比较两个字段值的字段验证

I've created a content type using two fields "capacity" and "count".

In a custom module I'd like to validate that field "count" should be less than field "capacity".

function MYMODULE_node_form_validate($form, &$form_state) {

  $capacity = $form['capacity']['#value'];
  $count = $form['count']['#value'];

  if ($count > $capacity) {
    form_set_error('title', 'Not possible');
  }
}
  • 写回答

1条回答 默认 最新

  • duanlie4621 2018-03-27 09:09
    关注

    First add a custom validation function, then fire your logic from there and prevent the form from further processing if necessary. Replace MYMODULE and MYCONTENTTYPE with your machine names.

    /**
     * Implements hook_form_BASE_FORM_ID_alter().
     */
    function MYMODULE_form_node_form_alter(&$form, &$form_state, $form_id) {
    
      // Find the content type of the node we are editing.
      $content_type = $form['#node']->type;
    
      if ($content_type == 'MYCONTENTTYPE') {
    
        // Add an additional custom validation callback.
        $form['#validate'][] = 'MYCUSTOM_FORMVALIDATION';
      }
    }
    
    /**
     * Custom MYCONTENTYTPE node form validation.
     */
    function MYCUSTOM_FORMVALIDATION($form, &$form_state) {
    
      // Better check isset() and !empty() first. Depends on your needs.
      // Convert values to comparable numbers.
      // Maybe you prefer intval() or some other logic. Depends on your needs.
      $field_a = floatval($form_state['values']['field_a'][LANGUAGE_NONE][0]['value']);
      $field_b = floatval($form_state['values']['field_b'][LANGUAGE_NONE][0]['value']);
    
      // Stop the form from further processing if field A < than field B.
      if ($field_a < $field_b) {
        form_set_error('stop', t('Field A shall be greater then Field B'));
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀