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 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!
  • ¥15 Python程序,深度学习,有偿私
  • ¥15 扫描枪扫条形码出现问题
  • ¥35 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?