I have created a few checkout fields with similar data and they are required.
add_filter('woocommerce_checkout_fields', 'custom_woocommerce_billing_fields', 50);
function custom_woocommerce_billing_fields($fields) {
$fields['billing']['billing_company'] = array(
'label' => 'Company',
'type' => 'text',
'class' => array( 'form-row-first' ),
'required' => true,
);
$fields['billing']['billing_OIB'] = array(
'label' => 'OIB',
'type' => 'text',
'class' => array( 'form-row-last' ),
'required' => true,
);
}
A customer has a radio button option to choose if he is buying as a private person or on behalf of a company. If he is buying for private purposes, then with JavaScript I will hide some of unneeded fields like company name and I also remove class name validate-required. If he is buying for a company, then I hide first name, last name etc. This code is bigger but I think you get the idea.
notNeededField.style.display = 'none';
notNeededField.classList.remove('validate-required');
But this doesn't work completely because WooCommerce probably does additional validation of each field in PHP. So even after I want to checkout as a private person, Woocommerce still gives me message that company name is required.
Is it possible to turn off/on validation on the fly with JavaScript and how?
Alternatively, what would be the best solution? Maybe to set required parameter on those fields as false and only do custom JavaScript validation?