Remove validation specific field based on the country on woocommerce checkout

Viewed 149

I need to make a specific field, in this case the VAT number, mandatory and not based on the country that the user selects.

In my case, the VAT number must be made optional only in Great Britain and Switzerland.

Here is the code I entered, which works immediately when the page loads, but then when the country changes it no longer executes the conditions.

It just does one interaction, it's like it does the if statement only once.

add_filter('woocommerce_checkout_fields', 'custom_billing_fields', 1000, 1);
function custom_billing_fields( $fields ) {


$user = wp_get_current_user();

global $woocommerce;
$country = $woocommerce->customer->get_country();

//Check user role
//If a company, so professionista role
if ( in_array( 'professionista', (array) $user->roles && $country !== 'GB')) {
        
//get mandatory VAT field
$fields['billing']['billing_vatcode']['required'] = true;
    
}

elseif($country == 'GB'){
    
//remove mandatory VAT field
$fields['billing']['billing_vatcode']['required'] = false;
    
}

//if is a classic client
else {

//remove other field
unset($fields['billing']['billing_vatcode']);   
unset($fields['billing']['billing_pecaddress']);
unset($fields['billing']['billing_recipientcode']);


}

return $fields;

 }

I realized that maybe the problem is due to the fact that only with Javascript you could do something like this and I tried:

add_action( 'woocommerce_after_checkout_form', 'bbloomer_shows_notice_shipping' );

function bbloomer_shows_notice_shipping(){
 
?>

<script>
    jQuery(document).ready(function($){

        // Set the country code (That will display the message)
        var countryCode = 'GB';

        $('select#billing_country').change(function(){

            selectedCountry = $('select#billing_country').val();
              
            if( selectedCountry == countryCode ){
        
            $("p#billing_vatcode_field").removeClass("validate-required");
                $("p#billing_vatcode_field").removeClass("woocommerce-validated");
            }
            else {
                $("p#billing_vatcode_field").addClass("validate-required");
                $("p#billing_vatcode_field").addClass("woocommerce-validated");
             }
        });

    });
</script>

<?php

}

But it seems that, even reading around, it is not possible to remove the validation, by removing the class, at the time of checkout.

I need help.

Thanks!

0 Answers
Related