Magento – Toggle “required/not required” field in checkout

checkoutmagento2validation

I have added a custom field in checkout called "Area". Area field is required by default, but I'd like to change that based on the selected country.

If customer selects a country other than FR, then Area field should become optional (not required).

Can you help me do that?

require([
    "jquery",
    "jquery/ui",
    "domReady!"
],
function($) {
    function load() {

        var country_select = $('div#shipping-new-address-form>div[name="shippingAddress.country_id"]>div.control>select.select');

        country_select.change(function () {
            var selected_country = $('div#shipping-new-address-form>div[name="shippingAddress.country_id"]>div.control>select.select :selected').val();

            if(selected_country == 'FR'){
                // make Area field required
            }else{
                // make Area field optional
            }

        });
    }
});

Best Answer

Add 'validation' index in layout processor for your custom field as

'validate-area-required' => true,

And add your mixin validation-mixin.js with

define([
    'jquery',
    'Magento_Ui/js/lib/validation/utils'
], function ($, utils) {
    "use strict";

    return function (validator) {            
        validator.addRule(
            'validate-area-required',
            function (value) {
                var selected_country = $('div#shipping-new-address-form>div[name="shippingAddress.country_id"]>div.control>select.select :selected').val();
                if(selected_country == 'FR'){
                    return true;
                }else{
                    return false;
                }

            },
            $.mage.__('Required field.')
        );
        return validator;
    }
});

Not tested...Hope it will work!

Related Topic