AddressErrors

The AddressErrors dictionary is used by the Payment Request API to report validation errors in a physical address (typically a billing address or a shipping address). Any members which are present indicate that a validation error occurred for the member of the same name in an address described using PaymentAddress.

AddressErrors is the type of the object returned by shippingAddressErrors in the object passed into PaymentRequestUpdateEvent.updateWith() by the shippingaddresschange event handler if a change to the address resulted in a validation error occurring.

See the examples below to see how this works.

Properties

addressLine

A DOMString which, if present, indicates that the addressLine property of the PaymentAddress could not be validated. The contents of the string provide a human-readable explanation of the validation failure, and ideally suggestions to correct the problem.

city

A DOMString which, if present, indicates that the city property of the PaymentAddress could not be validated. The contents of the string provide a human-readable explanation of the validation failure, and ideally suggestions to correct the problem.

country

A DOMString which, if present, indicates that the country property of the PaymentAddress could not be validated. The contents of the string provide a human-readable explanation of the validation failure, and ideally suggestions to correct the problem.

dependentLocality

A DOMString which, if present, indicates that the dependentLocality property of the PaymentAddress could not be validated. The contents of the string provide a human-readable explanation of the validation failure, and ideally suggestions to correct the problem.

organization

A DOMString which, if present, indicates that the organization property of the PaymentAddress could not be validated. The contents of the string provide a human-readable explanation of the validation failure, and ideally suggestions to correct the problem.

phone

A DOMString which, if present, indicates that the phone property of the PaymentAddress could not be validated. The contents of the string provide a human-readable explanation of the validation failure, and ideally suggestions to correct the problem.

postalCode

A DOMString which, if present, indicates that the postalCode property of the PaymentAddress could not be validated. The contents of the string provide a human-readable explanation of the validation failure, and ideally suggestions to correct the problem.

recipient

A DOMString which, if present, indicates that the recipient property of the PaymentAddress could not be validated. The contents of the string provide a human-readable explanation of the validation failure, and ideally suggestions to correct the problem.

region

A DOMString which, if present, indicates that the region property of the PaymentAddress could not be validated. The contents of the string provide a human-readable explanation of the validation failure, and ideally suggestions to correct the problem.

sortingCode

A DOMString which, if present, indicates that the sortingCode property of the PaymentAddress could not be validated. The contents of the string provide a human-readable explanation of the validation failure, and ideally suggestions to correct the problem.

Obsolete properties

These properties have been removed from the specification and should no longer be used.

languageCode

A DOMString which, if present, indicates that the languageCode property of the PaymentAddress could not be validated. The contents of the string provide a human-readable explanation of the validation failure, and ideally suggestions to correct the problem.

Usage notes

Keep in mind that some violation errors may be outside the ability of the user to fix. Try to avoid asking the user to make corrections to things they can't change, and there may be situations in which you need to allow validation errors to be accepted anyway (for example, if you validate addresses against a postal service database and a new home has been built and its address is not yet in the database).

Examples

Snippet: Limiting destination countries

This first example is just a snippet showing an implementation of the event handler for the shippingaddresschange event which checks to be sure the chosen address is located within one of a limited number of countries.

function handleAddressChange(ev) {
  const validCountries = ["US", "CA", "GB", "JP", "CN", "MX"];

  const genericAddressError = "Unable to ship to the given address. Please check for any errors.";
  const invalidCountryError = "At this time, we only ship to the United States, Canada, Great Britain, Japan, China, and Germany.";

  let shippingAddress = ev.target.shippingAddress;
  let shippingAddressErrors = {};
  let updateDetails = {};

  if (!validCountries.includes(shippingAddress.country)) {
    ev.target.shippingOptions = [];
    shippingAddressErrors.country = invalidCountryError;

    updateDetails = {
      error: genericAddressError,
      shippingAddressErrors,
      ...defaultPaymentDetails
    };
  }

  ev.updateWith(updateDetails);
}

See Handling address changes for a description of how this code works.

Complete example

Here we'll see a complete, working version of the example above (except of course that it's not connected to an actual payment handler, so no payments are actually processed). In the example, we're handling a donation to an organization that will be sending a "thank you" gift to the donor, so it requests shipping information along with allowing the donation payment itself.

JavaScript

Payment Request data

First, we declare the variables supportedHandlers, which is compatible with PaymentMethodData, and defaultPaymentDetails, which is an object containing the properties described in PaymentRequestUpdateEvent.updateWith.

let supportedHandlers = [
  {
    supportedMethods: "https://example.com/pay"
  }
];

let defaultPaymentDetails = {
  total: {label: 'Donation', amount: {currency: 'USD', value: '65.00'}},
  displayItems: [
    {
      label: 'Original donation amount',
      amount: {currency: 'USD', value: '65.00'}
    }
  ],
  shippingOptions: [
    {
      id: 'standard',
      label: 'Standard shipping',
      amount: {currency: 'USD', value: '0.00'},
      selected: true
    }
  ]
};

supportedHandlers describes the supported payment handlers and the details for those. In this example, only the Example Pay payment handler is supported.

defaultPaymentDetails describes the payment being requested. A description of the total amount being requested (including a label and the currency used), a list of the line items (in this case only one, "Original donation amount"), and a list of shipping options available; in this case only one.

Process the payment

The main payment processing code is found in the process() method, up next.

let request;

function process() {
  let options = {requestShipping: true};

  try {
    request = new PaymentRequest(supportedHandlers, defaultPaymentDetails, options);
    // Add event listeners here.
    request.onshippingaddresschange = handleAddressChange;
    // Call show() to trigger the browser's payment flow.
    request.show().then(function(instrumentResponse) {
      // Do something with the response from the UI.
      console.log("Got response!");
    })
    .catch(function(err) {
      // Do something with the error from request.show().
      console.error(`Error from show(): ${err}`);
    });
  } catch (e) {
    // Catch any errors from trying to create the PaymentRequest object.
  }
}

This code creates a new PaymentRequest, providing the supported handlers and payment options we set up above, as well as additional options (in this case, that we want to ask for shipping information).

After that, we set up the handler for the shippingaddresschange event so we can validate address information and call the request's show() method to start running the payment UI.

Handling address changes

The handleAddressChange() method, called when shippingaddresschange events occur, is where we'll look to see if the country is one of those we allow as shipping destinations.

function handleAddressChange(ev) {
  const validCountries = ["US", "CA", "GB", "JP", "CN", "MX"];

  const genericAddressError = "Unable to ship to the given address. Please check for any errors.";
  const invalidCountryError = "At this time, we only ship to the United States, Canada, Great Britain, Japan, China, and Germany.";

  let shippingAddress = ev.target.shippingAddress;
  let shippingAddressErrors = {};
  let updateDetails = {};

  if (!validCountries.includes(shippingAddress.country)) {
    ev.target.shippingOptions = [];
    shippingAddressErrors.country = invalidCountryError;

    updateDetails = {
      error: genericAddressError,
      shippingAddressErrors,
      ...defaultPaymentDetails
    };
  }

  ev.updateWith(updateDetails);
}

The shippingaddresschange event doesn't receive the PaymentRequest object directly, so we fetch it from the target property of the event. If the request's shippingAddress has a value for country which isn't in the array validCountries, we generate the error.

That's done by removing all shipping options currently set on the request, then set up an object named shippingAddressErrors which contains a country property which is an error message describing why the stated country isn't being permitted as a value.

Then an object is created with its error set to a generic message about address errors and with the reset of the object's values taken from shippingAddressErrors, and, using "...defaultPaymentDetails" as the final entry in the object, the remainder of the properties' values are taken from defaultPaymentDetails.

The final step is to call the event's updateWith() method, passing along the updateDetails object. This lets the Payment Request API know to present the specified error or errors but to allow the user to keep trying to edit the address.

Setting up the Donate Now button

This code creates a handler for the load event on the window which in turn adds the needed click event handler to the "Donate Now" button so that clicking it starts the payment process.

window.addEventListener("load", function(ev) {
  document.getElementById("pay").addEventListener("click", process, false);
}, false);

See addEventListener() for information about event handlers and how they work.

HTML

Here's the simple HTML for this example.

<p>Donate US $65 to our worthwhile cause and we will send you a totally
not-useless gift as a token of our thanks!</p>
<button id="pay">Donate Now</button>

Result

The final product is below.

Note: if you have content blocking features enabled in your browser, the example may not work inline below. In that case, you can view the example on its own page.

Specifications

No specification found

No specification data found for api.AddressErrors.
Check for problems with this page or contribute a missing spec_url to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

Browser compatibility

No compatibility data found for api.AddressErrors.
Check for problems with this page or contribute missing data to mdn/browser-compat-data.