Magento2 – Add Extra Validation Rules for Existing Shipping Carrier

magento2.3shipping-methodsvalidation

This question is about javascript carrier validation in the checkout page. Depending on the validation result, some carriers may disappear from the displayed list if validation failed for them.

I found documentation about how to Add custom shipping carrier validations. This doc explains how to create from scratch a brand new validator and its own validation rules and how to register them and how to add them in the checkout layout etc. etc…
The point is : I don't need to create a new validator from scratch. The carrier already exists, its validator too. I just want to add an extra validation rule to the existing ones (and fyi, I want this carrier validation to fail if shipping address telephone is not a mobile phone).

Is there a way to inject my own rule in the existing ones (with a mixin maybe ?) or do I have to go through the full creation as described in the official doc, to end up pushing an additional validator for this carrier ?

Best Answer

In Your Shipping Model File(eg. Career.php) add below like condition

public function collectRates(RateRequest $request)
{
        /**
         * here add custom condition and return false if not matching in your condition
         */
        if ($telephone = $quote->getShippingAddress()->getTelephone()) {
            if($telephone != 'your_variable'){
                return false;   // it will not execute furthure code
            }           
        }

        // here your shipping main code
}