Validate Before Submitting
Overview
This guide explains how to implement address validation using the AddressLookup library before allowing a form submission. The goal is to ensure users select a valid address, enhancing data integrity and user experience.
Code Setup
let shouldFormSubmit = false;
AddressZen.AddressLookup.setup({
apiKey: "ak_test",
outputFields: {
line_1: "#line_1",
line_2: "#line_2",
city: "#city",
state: "#state",
zip_plus_4_code: "#zipcode",
},
onLoaded: function () {
const form = this.input.closest("form");
if (form === null) return;
form.addEventListener("submit", (e) => {
if (shouldFormSubmit === false) {
e.preventDefault();
// Add custom action - E.g. show a warning
alert("Please select an address before proceeding");
return false;
}
});
},
onAddressPopulated: function () {
shouldFormSubmit = true;
},
});
How it Works
When a user interacts with the input fields for address data and selects a valid address, the AddressLookup's onAddressPopulated callback is fired, setting shouldFormSubmit to true.
If a user attempts to submit the form before selecting a valid address, the form's submit event is intercepted. A message is displayed, instructing the user to complete the address fields.
Once a valid address is selected and populated, the user can submit the form successfully.
Loading...