在 WooCommerce 中为动态生成的字段添加验证

问题描述

我正在创建一个自定义 wordpress 结帐页面,该页面会根据购物车中的产品进行更改,我需要为表单字段添加验证,这些表单字段由 foreach() 循环动态创建

不确定如何为动态生成的字段创建验证以及如何保存这些字段。

这是我的代码

add_action( 'woocommerce_after_order_notes','custom_checkout_field' );
function my_custom_checkout_field( $checkout ) {
    /**
    /* Some prevIoUs logic,which returns $items array with this. I will generate it here manually to showcase the structure of $items array. rand() is there just to make these keys unique every time the script is run.
    */

    $i = rand(1,100);
    $j = $i + 1;
    $items = array(
        "querstion".$i."" => array(
            "option 1-1","option 1-2","option 1-3"
        ),"querstion".$j.""=> array(
            "option 2-1","option 2-2","option 2-3","option 2-4"
        ),);

    foreach( $items as $key => $val ) {           
        woocommerce_form_field('Box_field-' . $key,array(
            'type' => 'radio','options' => $val,'class' => array(
                'form-row-wide','custom-radio'
                ),'label' => __( $key ),'required' => true,),$checkout->get_value( 'Box_field-'.$key ));

        /**
        /* Here is the validation,which doesn't work
        */

        add_action( 'woocommerce_checkout_process',function() use ($key) { 
            if ( isset( $_POST['Box_field-' . $key] ) ) {
                $domain = 'woocommerce';
                $Box_field = $_POST['Box_field-' . $key];
    
                // Empty
                if ( empty ( $Box_field ) ) {
                    wc_add_notice( __( 'My error message',$domain ),'error' );
                }    
            }
        });
    }

}

有什么想法吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)