How to add country based validations in Address form?

Requirement

When adding a new [billing or shipping] address, can we remove all the countries except Canada and United States?

Solution

To implement country-based validation on address records, a client script can be created and attached to the custom code section of the custom address form. This script ensures that users can only select “United States” (US) or “Canada” (CA) in the country field. 

Important Note:

The custom address form behavior is controlled by the list of countries configured under the “Country” tab in the form setup.

If you want this validation to apply to all countries, you must ensure that all countries are selected in the country list of the custom address form; otherwise, the script will not trigger for countries not included in that list.

Sample Code


 /**
 * @NApiVersion 2.x
 * @NScriptType ClientScript
 */
define([], function () {
    var suppressChange = false;

    function fieldChanged(context) {
        try {
            var currentRecord = context.currentRecord;
            var fieldId = context.fieldId;

            if (fieldId === 'country') {
                console.log('Field changed:', fieldId);
                var country = currentRecord.getValue({ fieldId: 'country' });
                console.log('Selected country:', country);

                var allowedCountries = ['US', 'CA'];

                if (!allowedCountries.includes(country)) {
                    console.warn('Invalid country selected:', country);
                    alert('Only addresses from United States or Canada are allowed.');
                    currentRecord.setValue({
                        fieldId: 'country',
                        value: 'US'
                    });
                }
            }
        } catch (e) {
            console.error('Error in fieldChanged:', e);
        }
    }

     function saveRecord(context) {
        try {
            var currentRecord = context.currentRecord;
            var country = currentRecord.getValue({ fieldId: 'country' });

            console.log('Country at save:', country);

            var allowedCountries = ['US', 'CA'];

            if (country && !allowedCountries.includes(country)) {
                alert('Only addresses from United States or Canada are allowed.');
                return false;
            }

            return true;
        } catch (error) {
            console.error('Error in saveRecord:', error);
            return false;
        }
    }

    return {
        fieldChanged: fieldChanged,
        saveRecord: saveRecord
    };
});

Leave a comment

Your email address will not be published. Required fields are marked *