woocommerce offtopic – How to conditionally validate billing field on checkout and edit address pages?

Question

I used this code to add a checkbox and a required field:

add_filter('woocommerce_billing_fields', function ($fields) {

    $fields['billing_user_type'] = [
        'label' => __('Legal entity?', 'woocommerce'),
        'placeholder' => '',
        'required' => false,
        'clear' => false,
        'type' => 'checkbox',
        'priority' => 40,
        'class' => ['form-row-wide form-check billing-user-type']
    ];

    $fields['billing_urc'] = [
        'label' => __('Unique registration code', 'woocommerce'),
        'placeholder' => __('Ex.: 1234567', 'woocommerce'),
        'required' => true,
        'clear' => false,
        'type' => 'text',
        'priority' => 42,
        'class' => ['form-row-first user-type-field hidden']
    ];
}

My issue is, that on the checkout and edit address pages, the validation fails, even if the checkbox is not checked (as expected), but I want to validate the value of the field only if the checkbox is checked. I know that I can do it if I set the field to not required, by using the woocommerce_checkout_process and woocommerce_after_save_address_validation hooks, but is it really impossible to do it this way? (by setting the field as required, and skipping validation)

0
csba 5 months 2022-07-22T08:05:59-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse