New! Now you can verify addresses as users enter them on your website simply by adding a single line of Javascript to your page. No programming necessary.
Jump to:
Example
Requirements
- jQuery 1.5.1 or newer (quick download here)
Install
Paste just one of these into the <head> portion of your page (after jQuery) or
just before the </body> tag. Replace HTML_KEY with an
HTML key from your account.
<script type="text/javascript" src="//d79i1fxsrar4t.cloudfront.net/jquery.liveaddress/2.3/jquery.liveaddress.js"></script>
<script type="text/javascript">jQuery.LiveAddress({ key: "HTML_KEY", debug: true });</script>
Minified, for live production use:
<script type="text/javascript" src="//d79i1fxsrar4t.cloudfront.net/jquery.liveaddress/2.3/jquery.liveaddress.min.js"></script>
<script type="text/javascript">jQuery.LiveAddress("HTML_KEY");</script>
Then just make sure it works. Turn "debug" mode on to make this easier. The most likely cause of failure is that the automapping didn't complete successfully. If that's the case, map the fields manually. The second-most-likely cause of failure is interference from other Javascript on the page or dropdown menus (see notes below).
Important Note #1 — Dropdowns
If any address fields in your form are dropdown menus (common with "State" fields), you are responsible to ensure compatibility and correct behavior. The actual "value" attributes in your <option> tags must be upper-case, 2-character, official state abbreviations (e.g. "FL"). Having any other values (arbitrary numbers, lower-case, full state names, etc.) may interfere with the behavior of the plugin and potentially result in extra lookups on your account. Generally, we recommend against using drop-downs to constrain user input—you're verifying the input addresses anyway, right?
Important Note #2 — Other Javascript
If your page has any other Javascript wired up to the form or functionality of the page in any way, including scripts which enhance the UI of default form elements, among anything else, it is your responsibility to make sure that your page is compatible with the plugin. We cannot account or be responsible for all possible scenarios. While we do officially support the plugin, it is presented "as-is."
Advanced
The rest of this documentation will be helpful if auto-mapping (the process which automatically finds address fields in your forms) fails or if your use case is more advanced. Most of this is tailored to developers familiar with Javascript and jQuery.
Initialization
The plugin must be initialized before it can be useful. This is done by calling the
jQuery.LiveAddress() function and passing in at least an HTML Key from your account
so that API calls can be authenticated. You should only initialize once.
An object is returned that exposes functions for you to use.
-
DEFAULT
var liveaddress = $.LiveAddress("HTML-KEY"); -
CUSTOM (example configuration shown)
var liveaddress = $.LiveAddress({ key: "HTML-KEY", debug: true });Where the parameter is an object with any of these properties:
key:Required. Your HTML key.-
autoMap:Default: true. If you want to use auto-mapping but want to auto-map fields later on (by callingmapFields()), set this to false. If you want to manually map fields, you do not need to specify false, since providing your own map implies that auto-mapping is off. -
candidates:Default: 3. The number of matches to return when the address response is ambiguous. Note: If you set this to 1, all ambiguous addresses will appear to be perfectly valid instead. -
addresses:An array of objects representing addresses. If automapping fails, use this. For example:[ { street: '#streetInput', street2: '#street2Input', city: '#cityInput', state: '#stateInput', zipcode: '#zipInput' } ]Where each value is a selector for the HTML element which contains that value. Generally this selector will be an ID like
#fieldID. Separate multiple address objects (bounded by{and}) with commas, without a comma after the last object. If automapping fails, this is a sure way to have the fields mapped correctly.Note: Valid field names are those accepted as input by our API according to the specs, for all fields between "street" and "urbanization" inclusive and country. You may also give each address a unique "id" for identifying them later on (see example right below). If you don't assign the address an ID, the plugin will do so internally for its own use.
Here's a full example of initializing by passing in a map for a couple addresses with debug mode on, and a unique ID assigned to both addresses:
$.LiveAddress({ key: 'YOUR_HTML_KEY', debug: true, addresses: [{ id: 'billing', // IDs are not part of the address street: '#street1', street2: '#street2', // Not all these fields are required city: '#city', state: '#state', zipcode: '#zip', country: '#country' }, { id: 'shipping', // IDs are optional, but can be helpful street: '#addrTb' }] });The second address is a single-line (freeform) address, which is also supported.
-
ui:Default: true. Provide and execute the default UI for handling address verification results. Disable this to use your own interface. Important: If you disable this, valid addresses will still work, but ambiguous and invalid addresses will have no way to be handled. Thus, it's vital that you bind your own event handlers to deal with these situations if not using the built-in UI. -
timeout:Default: 5000. Number of milliseconds before an API request is considered failed if no response has been received. 5000ms is 5 seconds. -
autoVerify:Default: true. Verify the address as the user types it in, once there is enough information. This will only happen once per address before the form is submitted to avoid annoying prompts. -
submitVerify:Default: true. ver 2.3+ Verify addresses in a form when the form is submitted. If you set both this andautoVerifyto false, no validation will occur automatically at all. -
requestUrl:Default: https://api.smartystreets.com/street-address ver 2.2.3+ The URL to which API requests are made. You can change this to proxy requests through your own server, thus allowing you to hide your API key, monitor requests, and more, but it must act and look exactly like our original endpoint. -
debug:Default: false. If true, debug and log info will be printed to the console, and mapped fields will be highlighted and labeled. -
ambiguousMessage:Default: "Choose the correct address" The message to display when an address is ambiguous. Should be short. -
invalidMessage:Default: "Address not verified" The message to display when an address is invalid. Should be short. -
fieldSelector:Default: "input[type=text], input:not([type]), textarea, select" — The selector which is used to identify input fields inside each form. Do not attempt to use this to map the form fields. -
submitSelector:Default: "[type=submit], [type=image], [type=button]:last" — The selector which is used to identify submit buttons inside each form. If not already done, addresses should be verified (or at least accepted) when the form submits. If they aren't, then make sure this selector is finding your submit buttons correctly. You might even set this to be the ID of the submit button:"#mySubmitButton"
-
FILTERED (limits the mapping of fields to within, but not including, a certain selector)
var liveaddress = $('.some-selector').LiveAddress( ... );
Functions
The object returned by the initialization exposes the functionality of this plugin.
For example, if you saved the return value from above in a variable named liveaddress,
you would use the functions below like liveaddress.verify(...); in your
code.
mapFields([map | "auto"])Maps address input elements to the type of data they contain. This is useful if important DOM elements are injected into your page after the document is done loading. You may pass in one of these:
- An array of objects which maps field types to their element's selector.
See the
addressesproperty above for the structure. - The string
"auto"to force an automap, even if you disabled it. - Nothing, which uses a previous map if passed in during initialization, or auto-maps if enabled. Otherwise it does nothing.
Functions like this which use the DOM should not be executed unto the document is ready.
- An array of objects which maps field types to their element's selector.
See the
on(eventType, callback(event, data, previousHandler))Similar to jQuery's "on" function, this is specifically for binding your own handlers to LiveAddress' custom events.
eventTypeis the name of the event, andcallbackis your own function into which three arguments are passed: the event object, useful data, and a reference to the previousHandler. See events for more details.The benefit of using this "on" function instead of jQuery's is that your handler will be fired first, allowing you to manipulate the process with more freedom. If you want the previous handler to fire, then be sure to call it:
previousHandler(event, data)setKey(htmlKey)Change the working HTML key, with the new one passed in as a string. This is only useful in certain debugging situations.
deactivate(addressID)ver 2.1+"Turns off" an address, so it won't be verified when it changes or when the form is submitted. This can be very useful on checkout pages for options like "Shipping same as billing." However, calling
verify()directly will still verify an inactive address.addressIDshould be the ID of an address which is specified during mapping.activate(addressID)ver 2.1+"Turns on" an address, so that it will be verified when the form is submitted or the address changes.
makeAddress(addressData)Constructs a new Address object and returns it.
addressDatashould be a string containing the address, or an object mapping fields to values. The field names are the same as described above. For instance:var address = liveaddress.makeAddress({ street: "123 Main St", zipcode: "12345" });Addresses constructed in this manner are independent of any mapped fields. You would make Addresses primarily for non-GUI use.verify(address | address_id[, callback(response)])Performs a request to the LiveAddress API given an input address, and invokes
callback, giving it a Response object.addresscan be a string (a street address or an address ID) or object, mapping fields to values (like above). It should not be an Address object, as this is merely an Address-agnostic way of verifying one. This function is asynchronous and does not return a value. Usage example:liveaddress.verify({ street: "123 Main St", secondary: "Unit 4", city: "Detroit", state: "MI" }, function(response) { console.log(response, response.raw); });Remember, the API's raw JSON response is wrapped in a Response object which is passed into the callback function. Note: Once the callback is executed, events stop firing for the verification of that address, as the handling is entirely up to the callback. To keep the Address event-based, don't pass in a callback.
Wrapper Objects
This plugin exposes two main objects which are very helpful.
An Address object represents an address as input.
A Response object represents address output
from the API, standardized and verified. Both objects have
different behaviors, purposes, and functions, and both are
used heavily internally.
Address
Address objects are obtained by calling makeAddress(...)
(documented above) or received by argument to an event
handler.
id()Returns the unique ID associated with this Address object.
set(field, value[, updateDomElement, keepState, sourceEvent])Sets the value of
fieldin the address tovalue.updateDomElement, if true, will change the value of the input element on the page (if there is one associated with the field). IfkeepStateis true, the state of the address ("changed" or "accepted") will not be changed.sourceEventmay be an event object which caused this "set" (change) to happen.get(field)Gets the value stored within the address given a particular
field(such as "street", "zipcode", etc, as above).verify([callback])Invokes verification on this address. Supply an optional callback function to which the Response will be passed if the request succeeds. If you supply a callback, events will stop firing for this address verification invocation once a response is received: it will be up to your callback to handle the response after that point. (The address is not automatically updated to reflect the verification results.)
undo([updateDomElement])For each field in the address, switches the current value with the previous value. If
updateDomElementis true or undefined, the value of the DOM element associated with each field (if exists) will be updated to reflect the change.abort(event[, keepAccept])Resets an address, so to speak, so that it can be run through the verification process again from the beginning. This is often used in your own event handlers when you want to abort the verification process. Pass in the
eventto make sure it stops firing other handlers. This function will automatically "un-accept" the address. If you want the address to stay "accepted" for some reason, setkeepAccepttotrue. See events.enoughInput()To verify an address, the API needs street and city/state or ZIP Code, or similar combination. This looks at the address to make sure there's enough input in the right fields to be recognized by the API as a complete address. This is done implicitly in any call to verify.
isDomestic()Returns
trueif the address is detected to be in the United States;falseotherwise.toRequest()Returns an object mapping fields to values, ready to submit to the API. Use this to "convert" the Address object to a format accepted by the LiveAddress API, though this function doesn't change the actual Address object; it only returns a new object.
replaceWith(replacement[, updateDomElement, event])Replaces the values in the address with those found in
replacement, which is an object returned from the API. (The API's raw response is an array of JSON objects; pass in just one of those objects. If an array of objects is passed in, the first object is used.) SetupdateDomElementto true to update any DOM element values associated with the address, andeventcan be the event which initiated the request.accept([data, showVerified])Marks the address as "accepted" (whether it was verified or not). Forms won't submit until every address is accepted. If intervening with an event handler, pass thru the
datato the next event. By default, calling this will turn the status indicator green. Set the second argument tofalseto prevent that.unaccept()Marks the address as "changed" (thus, not accepted) and raises the associated event.
toString()Returns a string representation of the values for each field of the address (separated by spaces).
isFreeform()Returns
trueif the address is considered to be a freeform (or "single-line") address, where all the data is contained in the "street" field. Returnsfalseotherwise.status()Gets the state of the address, whether it is "changed" or "accepted."
hasDomFields()Returns
trueif the address has DOM elements associated with any of its fields.getDomFields()Returns an associative array (an object) which contains references to the DOM elements for the fields in the address, if there are any.
syncWithDom([internalPriority])Set the internal values of the address's fields to the values in the DOM elements. This is only necessary if any changes have been made to the DOM elements' values programmatically with Javascript, which does not automatically fire the "change" event on the element. (To work around that, simply invoke the "change" event on a DOM element you're updating; then this should be unnecessary.) If
internalPriorityis true, then descrepencies between the DOM and the internal values (e.g. a value existing internally but not on the DOM) will keep the internal value.
Response
Response objects are obtained by calling verify(...)
(documented above) or received by argument to an event
handler. They contain the raw output of the LiveAddress API (as a JSON object)
and some helpful wrapper functions to make the output easier to interpret and use.
rawThis actually isn't a function; calling
rawon a Response object like this:response.rawwill give you access to the actual LiveAddress API output. Remember that the output from the API is always an array. Use this property to access specific values for particular candidates returned from the API, for example, coordinates:response.raw[0].metadata.latitude. Similarly, you can get the number of candidates byresponse.raw.length.chosenAlso not a function. Similar to
response.raw, butresponse.chosencontains only the portion of the raw response with the address the user has chosen during the verification process. If the address was simply valid, it contains the raw API response for that address. If it was ambiguous and the user chose a suggestion from the list, it contains the raw API response for that particular address. This property is only available after the after AddressWasValid or UsedSuggestedAddress events have fired, and only exists if a verified address was chosen. However, this still provides convenient access to the verified address (for example, to obtain lat/lon) no matter the path the user takes.
All the following functions return boolean true or false and
may optionally be passed an index from 0 to n-1, where n is the number of candidates returned,
to specify a particular candidate (if no index is passed in, then 0 is used):
isValid([index])The address is considered valid (only one candidate returned).
isAmbiguous([index])The address is considered ambiguous (more than one candidate returned).
isMissingSecondary([index])The address is valid, but is missing a secondary (unit/apartment/suite) number.
componentChanged([index])A component in the address was added, changed, or deleted to achieve a match. "Components" here means directional or suffix pieces.
betterAddressExists([index])The address is acceptable and valid, but a better, more preferred address exists.
isUniqueZipCode([index])The address was matched to a unique ZIP Code (street/unit data is basically irrelevant).
fixedAbbreviations([index])The address abbreviations were standardized (e.g. from "Street" to "St").
fixedZipCode([index])The correct ZIP Code was inserted into the ZIP Code field.
fixedSpelling([index])Adjusted the spelling in the street, city, or state fields to achieve standardization.
isBuildingDefault([index])The address is a default location in a building, like a lobby area.
isMilitary([index])Matched a military address.
hasExtraSecondary([index])The secondary information (apartment/suite/unit number) is not needed.
isLacsLink([index])The address was corrected to its proper form using LACSLink processing.
isCommercial([index])The address is a commercial address.
isResidential([index])The address is a residential address.
Events
This plugin is event-based. Custom events are raised throughout the lifetime of the script, particularly during the address verification process. These are the events which are raised, on a per-Address basis, in a general order:
| Event name | Possible Data | Description |
|---|---|---|
| First, these should fire in order: | ||
| FieldsMapped | — | Process which maps address fields to elements on the page is complete |
| MapInitializedver 2.3+ | — | Mapped addresses are now wired up to their input/UI elements and are ready and waiting |
| AddressChanged | address, field, sourceEvent, suppressAutoVerification, value | A field's internal value within an Address object has changed, usually because the
user types or changes their input in any mapped address field, or .set()
was called on the Address object
|
| VerificationInvoked | address | The verification process for an address is about to begin |
| RequestSubmitted | address | An address was just sent to LiveAddress API (asynchronously) |
| ResponseReceived | address, response, invoke | Response was barely received for an address; it is not yet examined |
| RequestTimedOut | address, invoke, status | This event fires only if no response is received after a period of time |
| Then any one of these, upon initial examination of the response: | ||
| AddressWasValid | address, invoke, response | The address matched only one valid address with no ambiguity |
| AddressWasAmbiguous | address, invoke, response, selectors | Matched at least 2 valid addresses, and ambiguity will need to be resolved |
| AddressWasInvalid | address, invoke, response, selectors | The input could not be matched to any valid addresses; empty response |
| If the input is ambiguous or invalid, these could happen: | ||
| OriginalInputSelected | address, invoke, response | The user chose to use their own input even though it's not valid (applies to: ambiguous or invalid) |
| UsedSuggestedAddress | address, chosenCandidate, invoke, response | User chose a suggested candidate address (applies to: ambiguous) |
| InvalidAddressRejected | address, invoke, response | User chose to go back to try fixing the bad address (applies to: invalid) |
| In the end... | ||
| AddressAccepted | address, invoke, response | An address was flagged as accepted; we're done with it unless it changes |
| Completed | address, invoke, response | The process is finished, at least for now (or the user aborted) |
Binding handlers to events
Use the on function to add a listener to any of these
events. Our on function guarantees that your handler gets executed
before the native handler, which is absolutely vital.
Here's a simple, practical example to accept only addresses which aren't missing a needed secondary number:
liveaddress.on("AddressAccepted", function(event, data, previousHandler) {
if (data.response.isMissingSecondary())
{
data.address.abort(event);
alert("Don't forget your apartment number!");
}
else
previousHandler(event, data);
});
Notice how the first argument is the name of the event, and the second is a function which accepts three parameters: the event object, data that's probably useful, and a previous handler.
To let the process continue, be sure to call previousHandler(event, data) and don't forget
to pass in event and data.
To cancel the string of events, simply don't invoke the previous handler. Usually this is accompanied
by calling abort on the address, like this: data.address.abort(event);—this
ensures the event won't fire other handlers later, and it resets the address for verification at another
time.
CSS / UI
The two main UI components are:
- A status indicator (like a "tag" attached to the last input field, with a check mark)
- A box to handle ambiguous and invalid addresses
You can customize the look and feel of the UI to match your website simply by adding style rules anywhere in your style sheet (CSS).
Table of style classes ver 2.3+| CSS class | Description |
|---|---|
.smarty-ui |
A class which contains any other plugin UI elements. This is a catch-all class. |
.smarty-dots |
The "loader" dots animation that shows while the address is verifying; hidden by default, but appears over the last input of the address. |
.smarty-popup |
The containing element of the little popup boxes that handle ambiguous or invalid addresses. These aren't true pop-up windows; they're just div elements positioned over the form. |
.smarty-popup-header |
The top part of a popup which holds the (short) message text and the close ("X") button. |
.smarty-popup-ambiguous-header |
Same as .smarty-popup-header, but only for popups dealing with ambiguous addresses. |
.smarty-popup-invalid-header |
Same as .smarty-popup-header, but only for popups dealing with invalid addresses. |
.smarty-popup-close |
The close ("X") button in the top-right corner of a little popup window. |
.smarty-choice-list |
The container for the list of options in a popup window. |
.smarty-choice-alt |
The container for the list of alternate options, visually less prominent, in a popup window. |
.smarty-choice-abort |
The link(s) in a popup window which abort the verification process (the user agrees to review the address). |
.smarty-choice-override |
The alternate option in a popup window for invalid addresses where the user certifies their address is correct. |
.smarty-tag |
The container for the "tag" attached to the last input field of each mapped address. The tag appears as an encircled, gray check mark. |
.smarty-tag-grayed |
The styles applied to the tag when the address is NOT in a verified state. |
.smarty-tag-green |
The styles applied to the tag when the address IS in a verified state. |
.smarty-tag-check |
The check mark displayed in the tag. |
.smarty-tag-text |
The text (such as "Verify", "Verified", or "Undo") that appear when a tag is hovered on. |
| CSS class | Description |
|---|---|
.smarty-dots |
The "loader" animation that shows while the address is verifying; it appears after the last field of the address (usually the ZIP code field). |
.smarty-container |
A containing div of any of the UI elements (verified, ambiguous, or invalid) (kind of a "catch-all" class) |
.smarty-address-verified |
The container (and text) of the "✓ Verified" message. It gets attached to the last field of the address (usually ZIP code). To hide this, you could set its visibility to hidden. |
.smarty-undo |
The link in the verified message that says "Undo" when you hover and lets the user undo an automatic change to their input. |
.smarty-address-ambiguous |
The main container for the UI that deals with ambiguous addresses. |
.smarty-address-invalid |
The main container for the UI that deals with invalid addresses. (This and the container for ambiguous addresses are very similar.) |
.smarty-ambiguous-message |
The container for the message displayed to the user when the address is ambiguous (default text is "Please choose the most correct address.") |
.smarty-invalid-message |
The container for the message displayed to the user when the address is invalid (default text is "Address could not be verified.") |
.smarty-choice |
One of the possible addresses that is presented to the user; this is an a tag. |
.smarty-use-original |
Similar to .smarty-choice, this is an a tag specifically for the option that lets the user use their original input instead of accepting an alternative (or the user certifies their address is correct even if it appears invalid). |
.smarty-choice-abort |
Similar to .smarty-choice, this is an a tag specifically for the option where the user will go back and review their address input. |
.smarty-abort |
For the a tag which appears in the top-right corner as a small "x", this aborts the verification process, much like the .smarty-choice-abort class above. |
If you experience difficulty getting your style rules to
override some
of the defaults,
try using the
!important
declaration. We also strongly recommend the use of
browser inspector tools, furnished with nearly every modern web browser:
Chrome,
Safari,
Firefox,
IE,
and
Opera.
Since the plugin is designed to survive in some hostile webpage environments, it was necessary to force certain
rules to preserve basic functionality. But we also wanted to make it easy to customize. The CSS
for our default UI is prepended to your <head> tag, which means rules after them will
cascade on top.
Contribute
Like all awesome source code, the ongoing development of this jQuery plugin is hosted on GitHub in the smartystreets/jquery.liveaddress repository. You can contribute by forking the project and making the changes of your wildest dreams. Then submit a pull request, and we'll review it.
Experimenting? The GitHub repository contains a nifty test runner for the jQuery plugin. It's a simple HTML file which you can open in your browser to test out different scenarios in a fairly isolated environment.
Shopping Carts
We will add instructions for specific shopping carts (BigCommerce, Volusion, 3dcart..) as we learn about them.
Version History
-
2.3.0 - 2.3.5 — Slick new UI (Feb. 2013) NEW!
The biggest change is a new UI that is now more visually appealing, polished, and neutral in tone (for a diversity of websites). The UI now includes a "status indicator" which turns green when the address is verified and has a "Verify" link so users can manually re-verify their input. Also some bug fixes and minor new features/functionality.
-
2.2.0 - 2.2.4 — Better submit and dropdown handling (Dec. 2012)
Along with significant stability improvements (particularly if you have drop-downs in your form), the plugin now binds to form
submitevents more robustly. Also new primitive support for auto-mapping "last line" fields. Auto-mapped addresses contain predictable IDs in the form of: "autoX", where X is the order it appears on the DOM (e.g. "auto1", "auto2", etc.) instead of random numbers. (Manual-mapped addresses without an ID declared are still random numbers.) -
2.1.0 - 2.1.2 — Custom IDs, bug fixes, and better mapping (Nov. 2012)
Addresses can be mapped with an "ID" which can be used to identify that address in your scripts. Added the
deactivate()andactivate()functions to turn verification off or on, respectively, for an address identified by passing in the ID. Added ability to pass an address ID into theverify()function. Also an assortment of relatively minor bug fixes. Version 2.1.2 now auto-maps "secondary" fields. -
2.0.0 - 2.0.3 — "LiveAddress API jQuery Plugin" (Oct. 2012)
Entirely re-engineered from scratch, this major update brings a host of new features and functionality, and is simple and extensible:
- Automapping. The LiveAddress API jQuery Plugin will automatically detect address input fields in your forms and do the rest for you. (But if it fails, you can give it a little push by telling it which fields to attach to.)
- Event-based. When something happens, custom events fire, so your own code can hook into the process at any point and even take complete control.
- Same endpoint. Our previous Javascript implementation used a different endpoint entirely from the LiveAddress API. Now, it's all the same: meaning the same results, the same performance, and the same power that you're used to.
- Better user experience. An improved appearance, together with more seamless functionality make users more satisfied overall. For example, we no longer ask the user to choose an address from a list when their input was valid and matched just one address.
- More logical. There's a lot of tricky logic involved with verifying addresses, but we've figured it out and abstracted a lot of it away so you don't have to deal with it.
- Single-line support. This plugin supports single-line/single-field/freeform addresses now, something that can really change the way we enter our addresses.
-
1.0 — "Address Entry Pro" / "QadApi" (Jun. 2007, so long ago...)
This first version allowed simple integration of address validation to website forms, but it wasn't an actual jQuery plugin and was difficult to extend or modify.