less than a minute read • Updated 2 hours ago
Add custom validation to your checkout
How to use the checkout-submit event to add custom JavaScript validation, including conditionally required fields.
When you need to block checkout unless a specific condition is met — like confirming a customer’s age, or requiring a field only in certain situations — you can add custom JavaScript validation to the checkout.
Steps
<script type="text/javascript">
FC.client.on("checkout-submit", function() {
});
</script>
For example, to require customers to be 18 or older based on a custom age field:
<script type="text/javascript">
FC.client.on("checkout-submit", function() {
var custAge = jQuery("#CustomerAge").val();
if (!isNaN(parseFloat(custAge)) && isFinite(custAge) && parseFloat(custAge) >= 18) {
return true;
} else {
alert("You must be over the age of 18 to purchase these products");
return false;
}
});
</script>
Conditionally requiring a field
You can also use this approach to make a standard field required only in certain situations — for example, requiring a phone number only when the cart contains shippable items. Add this to the footer section of your template configuration’s custom code option:
<script type="text/javascript" charset="utf-8">
function myCustomDisplayUpdate() {
var require_phone = 0;
for (p in FC.json.items) {
if (FC.json.items[p].delivery_type == "shipped") {
require_phone = 1;
}
}
if (require_phone == 1) {
FC.json.required_fields.push('shipping_phone');
FC.json.config.template_config.custom_checkout_field_requirements['billing_phone'] = "required";
}
}
if (FC.json.context == "checkout") {
FC.client.on("ready", myCustomDisplayUpdate);
}
</script>
Notes
Always return both
trueandfalsefrom yourcheckout-submitfunction. If you only set it tofalsein the failing case and never explicitly returntrue, the checkout won’t be able to proceed even when your condition passes.You can show and hide custom error messages the same way Foxy does for its own default fields.