You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Forminator表单复选框强制勾选指定数量问题求助

Forminator复选框强制选满指定数量的实现方案

问题背景

使用Forminator创建含12个复选框的表单,需求如下:

  • 1-10号复选框:每个必须且只能选1个选项
  • 11、12号复选框:每个必须选满8个选项

现有代码仅能限制复选框的最大勾选数量,无法阻止用户未选满8个就提交最后两个字段,需补充强制下限验证逻辑。

现有问题代码

<?php
/**
 * Plugin Name: [Forminator Pro] - Restrict select the multiple field(s).
 * Description: [Forminator Pro] - Restrict select the multiple field(s) (select/checkbox).
 * Author: Thobk @ WPMUDEV
 * Jira: SLS-918
 * License: GPLv2 or later
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
} elseif ( defined( 'WP_CLI' ) && WP_CLI ) {
    return;
}
add_action( 'wp_footer', function(){

    global $post;

    if( ! $post instanceof WP_Post || ! has_shortcode( $post->post_content, 'forminator_form' ) ) {
        return;
    }

    ?>
    <style>
        .forminator-ui .wpmudev-option-limit .wpmudev-disabled{
            color:#ddd!important;
        }
        .forminator-ui .wpmudev-option-limit .wpmudev-disabled span[aria-hidden]{
            border-color: #ddd!important;
        background-color: #ddd!important;
        }
    </style>
    <script type="text/javascript">
        
        ($=>{

            const _forminator_restrict_multiple_fields = {
                form_ids: [10097],
                limit: {
                    'checkbox-1': 1,
                    'checkbox-2': 1,
                    'checkbox-3': 1,
                    'checkbox-4': 1,
                    'checkbox-5': 1,
                    'checkbox-6': 1,
                    'checkbox-7': 1,
                    'checkbox-8': 1,
                    'checkbox-9': 1,
                    'checkbox-10': 1,
                    'checkbox-11': 8,
                    'checkbox-12': 8,
                },
                run : function( e, form_id ) {
                    if( _forminator_restrict_multiple_fields.form_ids.indexOf( form_id ) === -1 ){
                        return;
                    }
                    let _form = $( "#forminator-module-" + form_id );

                    _form.find('.wpmudev-option-limit').each(function(){
                        let _field = $(this),
                                checkbox_fields = _field.find( ":checkbox" );
                        if( checkbox_fields.length ){
                            checkbox_fields.on('change', function (e) {
                                let _parent = $(this).closest('.wpmudev-option-limit'),
                                        _parent_id = _parent.attr('id'),
                                        _selected = _parent.find(':checkbox:checked').length;
                                if( _parent_id in _forminator_restrict_multiple_fields.limit && _selected >= _forminator_restrict_multiple_fields.limit[ _parent_id ]){

                                    // save latest value.
                                    _field.data('latest_value', $(this).val() );
                                    // disable other options.
                                    _parent.find(':checkbox:not(:checked)').each(function(){
                                        $(this).prop('disabled', true).parent().addClass('wpmudev-disabled');
                                    });
                                }else{
                                    _parent.find(':checkbox:disabled').each(function(){
                                        $(this).prop('disabled', false).parent().removeClass('wpmudev-disabled');
                                    });

                                    _field.removeData('latest_value');
                                }
                            });
                        }

                        // auto remove previous value when riched the limit.
                        $(this).on('click', '.wpmudev-disabled', function(){
                            let _latest_value = _field.data('latest_value') ;
                            if( _latest_value ){
                                let _previous_opt = $(this).closest('.wpmudev-option-limit').find('input[value="'+ _latest_value +'"]');
                                if( _previous_opt.length ){
                                    _previous_opt.trigger('click');
                                    $(this).removeClass('wpmudev-disabled').find('input:disabled').removeAttr('disabled');
                                }
                            }
                        })
                    });
                }
            }

            $(document).ready(function(){
                $.each(_forminator_restrict_multiple_fields.form_ids, function(i, _form_id){
                    _forminator_restrict_multiple_fields.run(this,_form_id);
                });
                $(document).on( 'response.success.load.forminator', _forminator_restrict_multiple_fields.run );
            });
        })(jQuery);

    </script>

    <?php
}, 999 );

修改后的完整代码(含下限验证)

在原有代码基础上,添加表单提交拦截验证逻辑,确保必须选满指定数量才能提交:

<?php
/**
 * Plugin Name: [Forminator Pro] - Restrict select the multiple field(s).
 * Description: [Forminator Pro] - Restrict select the multiple field(s) (select/checkbox) with min/max limit.
 * License: GPLv2 or later
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
} elseif ( defined( 'WP_CLI' ) && WP_CLI ) {
    return;
}
add_action( 'wp_footer', function(){

    global $post;

    if( ! $post instanceof WP_Post || ! has_shortcode( $post->post_content, 'forminator_form' ) ) {
        return;
    }

    ?>
    <style>
        .forminator-ui .wpmudev-option-limit .wpmudev-disabled{
            color:#ddd!important;
        }
        .forminator-ui .wpmudev-option-limit .wpmudev-disabled span[aria-hidden]{
            border-color: #ddd!important;
        background-color: #ddd!important;
        }
        .forminator-error-message.custom-min-error {
            color: #dc3232;
            margin-top: 5px;
            font-size: 14px;
        }
    </style>
    <script type="text/javascript">
        
        ($=>{

            const _forminator_restrict_multiple_fields = {
                form_ids: [10097],
                limit: {
                    'checkbox-1': 1,
                    'checkbox-2': 1,
                    'checkbox-3': 1,
                    'checkbox-4': 1,
                    'checkbox-5': 1,
                    'checkbox-6': 1,
                    'checkbox-7': 1,
                    'checkbox-8': 1,
                    'checkbox-9': 1,
                    'checkbox-10': 1,
                    'checkbox-11': 8,
                    'checkbox-12': 8,
                },
                // 验证字段是否满足下限要求
                validateMinSelection: function(form) {
                    let isValid = true;
                    // 清除之前的错误提示
                    form.find('.custom-min-error').remove();

                    $.each(this.limit, (fieldId, requiredCount) => {
                        const field = form.find(`#${fieldId}`);
                        if (field.length === 0) return;

                        const selectedCount = field.find(':checkbox:checked').length;
                        if (selectedCount < requiredCount) {
                            isValid = false;
                            // 添加错误提示
                            field.after(`<div class="forminator-error-message custom-min-error">请选择至少 ${requiredCount} 个选项</div>`);
                        }
                    });

                    return isValid;
                },
                run : function( e, form_id ) {
                    if( _forminator_restrict_multiple_fields.form_ids.indexOf( form_id ) === -1 ){
                        return;
                    }
                    let _form = $( "#forminator-module-" + form_id );

                    // 原有上限限制逻辑
                    _form.find('.wpmudev-option-limit').each(function(){
                        let _field = $(this),
                                checkbox_fields = _field.find( ":checkbox" );
                        if( checkbox_fields.length ){
                            checkbox_fields.on('change', function (e) {
                                let _parent = $(this).closest('.wpmudev-option-limit'),
                                        _parent_id = _parent.attr('id'),
                                        _selected = _parent.find(':checkbox:checked').length;
                                // 清除当前字段的错误提示
                                _parent.next('.custom-min-error').remove();

                                if( _parent_id in _forminator_restrict_multiple_fields.limit && _selected >= _forminator_restrict_multiple_fields.limit[ _parent_id ]){

                                    _field.data('latest_value', $(this).val() );
                                    _parent.find(':checkbox:not(:checked)').each(function(){
                                        $(this).prop('disabled', true).parent().addClass('wpmudev-disabled');
                                    });
                                }else{
                                    _parent.find(':checkbox:disabled').each(function(){
                                        $(this).prop('disabled', false).parent().removeClass('wpmudev-disabled');
                                    });

                                    _field.removeData('latest_value');
                                }
                            });
                        }

                        $(this).on('click', '.wpmudev-disabled', function(){
                            let _latest_value = _field.data('latest_value') ;
                            if( _latest_value ){
                                let _previous_opt = $(this).closest('.wpmudev-option-limit').find('input[value="'+ _latest_value +'"]');
                                if( _previous_opt.length ){
                                    _previous_opt.trigger('click');
                                    $(this).removeClass('wpmudev-disabled').find('input:disabled').removeAttr('disabled');
                                }
                            }
                        })
                    });

                    // 监听表单提交事件,进行下限验证
                    _form.on('beforeSubmit', function(e) {
                        if (!_forminator_restrict_multiple_fields.validateMinSelection(_form)) {
                            e.preventDefault();
                            e.stopPropagation();
                            // 滚动到第一个错误位置
                            const firstError = _form.find('.custom-min-error').first();
                            if (firstError.length) {
                                $('html, body').animate({
                                    scrollTop: firstError.offset().top - 100
                                }, 300);
                            }
                        }
                    });

                    // 兼容AJAX提交的情况
                    $(document).on('forminator:form:submit:success', function(e, form) {
                        const currentFormId = parseInt(form.attr('id').replace('forminator-module-', ''));
                        if (_forminator_restrict_multiple_fields.form_ids.indexOf(currentFormId) === -1) {
                            return;
                        }
                        if (!_forminator_restrict_multiple_fields.validateMinSelection(form)) {
                            e.preventDefault();
                            e.stopPropagation();
                        }
                    });
                }
            }

            $(document).ready(function(){
                $.each(_forminator_restrict_multiple_fields.form_ids, function(i, _form_id){
                    _forminator_restrict_multiple_fields.run(this,_form_id);
                });
                $(document).on( 'response.success.load.forminator', _forminator_restrict_multiple_fields.run );
            });
        })(jQuery);

    </script>

    <?php
}, 999 );

关键修改说明

  1. 新增validateMinSelection方法:遍历所有目标字段,检查已勾选数量是否达到设定下限,未达标则添加错误提示
  2. 监听表单提交事件:在beforeSubmit和forminator:form:submit:success事件中触发验证,阻止不符合要求的提交
  3. 实时清除错误提示:勾选状态变化时清除对应字段的错误提示,提升用户体验
  4. 错误定位优化:提交失败时自动滚动到第一个错误位置,方便用户修正

使用注意事项

  • 确保所有12个复选框字段都已添加wpmudev-option-limit自定义类(在Forminator字段的「样式」标签中设置)
  • 替换代码中的form_ids: [10097]为你的实际表单ID
  • 确认limit对象中的字段ID(如checkbox-11)与Forminator后台的字段ID完全一致
  • 代码可通过主题functions.php或代码片段插件添加到站点

内容的提问来源于stack exchange,提问作者Giuliano Arena

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 03:39:55