Shopping cart

How to add custom shipping validations Magento 2

For developers, this shipping validator will trigger the checkout module to load (ajax) the shipping method details when users entering information.
This is an essential part of the bigger task of adding a custom shipping method to your Magento store.

In this article, we will take a look at Magento default/native carriers and then implement our own rules/validator.

The main method here is the validate method, this method is required for every validator.
The code is simple, what it does is checking whether those required fields have been fulfilled.

Here is the price information bases on each country/region

To test this validator, you should use TableRates as the only Shipping Carrier. Read more about Shipping Settings here

First, I add a $45 item to cart which will result in $15 shipping price, fill in all required information except for State/Province information.
When I change the State to Alaska (abbr: AK), the shipping method will reload.
Here is the video demonstrate step by step: https://www.screencast.com/t/PuK9hy5zYaP

Step 2: Create a custom rule/validator.

We need 3 files: 2 files to define getRules and validate functions. The last file is responsible for letting Magento knows the existence of our new code (Registering our validator).
Since we don’t have a new carrier, we will overwrite tablerate. Instead of using Magento’s tablerate rules and validator, it will use our created rules and validator.

Step 2.3: Registering our validator

To register our new validator, we must add it to the pool of validators.
To do this, in the Mageplaza/HelloWorld/view/frontend/web/js/view directory create a new tablerate.js file with the following content: