LiveAddress API jQuery Plugin

Verify and standardize addresses on website forms

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

Click to try these sample addresses:   Valid    Ambiguous    Invalid    Single-line
Address
Street address
City
State
ZIP code


Requirements




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.

Un-minified, for debugging and development only: <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.

  1. DEFAULT var liveaddress = $.LiveAddress("HTML-KEY");
  2. 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 calling mapFields()), 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 and autoVerify to 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"

  3. 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.




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.


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.

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):




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:

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.
[Table of style classes ver 2.0-2.2 ]   (click to toggle)
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