Table of Contents
Dynamically Require Shipping Phone Number
The following functionality allows you to dynamically require the shipping phone number depending on the shipping country of the customer.
Set phone to optional
To dynamically require the phone, it will need to be set as optional by default. You can do that from the Settings > Checkout page in the admin, or the “configuration” page in the legacy admin within the “Customize which checkout fields are shown and required” option.
Add Javascript
Copy and paste the following code into your store's “custom footer” option. This can be found on the Settings > Templates page in the admin, or on the “configuration” page of the legacy admin within the “Add custom header and footer code to your templates” option.
{% if context == "checkout" %}
<script type="text/javascript">
function requirePhone(params) {
var country = params.address.country;
var phone_required = FC.json.required_fields.indexOf("billing_phone");
if (country != "US" && phone_required == -1) {
FC.json.required_fields.push('billing_phone');
FC.json.config.template_config.custom_checkout_field_requirements['billing_phone'] = "required";
FC.Template("checkout").clearOutput();
FC.checkout.renderCustomerShipping();
} else if (country == "US" && phone_required > -1) {
FC.json.required_fields.splice(phone_required, 1);
FC.json.config.template_config.custom_checkout_field_requirements['billing_phone'] = "optional";
FC.util.removeError(params.address.prefix + "_phone");
FC.util.notifyErrors();
FC.Template("checkout").clearOutput();
FC.checkout.renderCustomerShipping();
}
}
FC.client.on("customer-address-change", requirePhone);
FC.client.on("ready.done", function() {
var addresses = [];
if (FC.json.shipping_address.has_shippable_products) {
addresses = FC.json.has_multiship ? FC.json.multiship_data : [FC.json.shipping_address];
}
if (FC.json.use_alternate_shipping_address || !FC.json.shipping_address.has_shippable_products) {
addresses.push(FC.json.billing_address);
}
for (var i = 0; i < addresses.length; i++) {
requirePhone({"address": addresses[i]});
}
});
</script>
{% endif %}