Magento – How to make the second address field required on checkout page on Magento 2

checkoutcustom-fieldjavascriptmagento2validation

Magento 2 has a option to extend the address field up to 4 fields.

This configuration can be found at:

Store->Configuration->Customer->Customer Configuration->Name and
Address Option

and there is a tab called Number of Lines in a Street Address.

Now all I want is to make the second field required like how the first field is required by default.

Does anyone know a solution?

Best Answer

Note that this form in the checkout is built with JavaScript / UI Components, so the solution provided by @Abhinav does not apply here (even though you should make those address fields on those other pages required as well).

The proper solution (for the checkout scenario) is to write a plugin for the layout processor and handle it from there:

In etc/frontend/di.xml:

<type name="Magento\Checkout\Block\Checkout\DirectoryDataProcessor">
    <plugin name="my_custom_checkout" type="Vendor\Module\Plugin\Magento\Checkout\Block\Checkout\DirectoryDataProcessor"/>
</type>

In Vendor\Module\Plugin\Magento\Checkout\Block\Checkout\DirectoryDataProcessor.php:

namespace Vendor\Module\Plugin\Magento\Checkout\Block\Checkout;

use Magento\Framework\Stdlib\ArrayManager;

/**
 * Class LayoutProcessor
 * @package Vendor\Module\Plugin\Magento\Checkout\Block\Checkout
 */
class LayoutProcessor
{
    /**
     * @var ArrayManager
     */
    protected $arrayManager;

    /**
     * LayoutProcessor constructor.
     * @param ArrayManager $arrayManager
     */
    public function __construct(
        ArrayManager $arrayManager
    ) {
        $this->arrayManager = $arrayManager;
    }

    /**
     * @param \Magento\Checkout\Block\Checkout\LayoutProcessor $subject
     * @param array $jsLayout
     * @return array
     */
    public function afterProcess(\Magento\Checkout\Block\Checkout\LayoutProcessor $subject, array $jsLayout)
    {
        $path = $this->arrayManager->findPath('street', $jsLayout);

        $streetNode = $this->arrayManager->get($path, $jsLayout);
        foreach ($streetNode['children'] as $idx => &$child) {
            // Make all address fields required:
            if (!isset($child['validation']['required-entry'])) {
                $child['validation']['required-entry'] = true;
            }
        }

        $jsLayout = $this->arrayManager->set($path, $jsLayout, $streetNode);

        return $jsLayout;
    }
}