Skip to content

Data validation

Learn about built-in validation and implement additional scenarios for Google Pay web.

Overview

The Google Pay component includes comprehensive validation to ensure data integrity and compliance with Google's requirements. All built-in validation is performed before creating payment requests and during the Google Pay flow. If validation fails, the SDK will throw an error with detailed information.

You can also easily build custom validation, depending on your business needs.

Built-in validation

By default, the Google Pay component validates that:

  • Fields marked as required are provided.
  • Payment request data meets Google Pay API specifications.
  • Currency codes, country codes, and amounts are formatted properly.
  • Allowed payment methods and networks are properly configured.
  • Transaction information is complete and valid.
  • Shipping address and billing address formats are correct.
  • Browser and device compatibility requirements are met.

Error codes

The Google Pay component returns structured error codes for different validation failures:

Error code DescriptionCommon causes
REQUIRED_FIELDA required field is missing.Missing mandatory configuration.
INVALID_AMOUNT_FORMATThe amount format is invalid.Non-string or negative amount.
INVALID_CURRENCY_CODEThe currency code is invalid.Non-ISO 4217 currency format.
INVALID_COUNTRY_CODEThe country code is invalid.Non-ISO 3166-1 alpha-2 format.
INVALID_PAYMENT_METHODPayment method configuration invalid.Unsupported payment method type.
INVALID_CARD_NETWORKSCard networks invalid.Unsupported network values.
INVALID_AUTH_METHODSAuthentication methods invalid.Unsupported auth method values.
INVALID_TRANSACTION_INFOTransaction info invalid.Malformed transaction data.
INVALID_TOTAL_PRICE_STATUSTotal price status invalid.Invalid status value.
INVALID_DISPLAY_ITEMSDisplay items invalid.Malformed line items.
INVALID_SHIPPING_OPTIONSShipping options invalid.Malformed shipping configuration.
GOOGLE_PAY_NOT_AVAILABLEGoogle Pay not available.Unsupported browser/device.

Validation example

// Example of handling validation errors
const googlePayConfig = {
  // ... configuration
  onError: (error) => {
    if (error.code === 'SDK0705') { // GOOGLE_PAY_CONFIGURATION_VALIDATION_FAILED
      console.error('Google Pay configuration validation failed:', error.message);
      
      // Handle specific validation errors based on error message
      if (error.message.includes('allowedPaymentMethods')) {
        console.error('Invalid payment methods configuration');
        showError('Payment configuration error. Please contact support.');
      }
      
      if (error.message.includes('totalPrice')) {
        console.error('Invalid total price format');
        showError('Payment amount error. Please refresh and try again.');
      }
      
      if (error.message.includes('gatewayMerchantId') || error.message.includes('merchant ID')) {
        console.error('Gateway merchant ID missing or invalid');
        showError('Payment system configuration error. Please contact support.');
      }
      
      // Log for debugging
      console.error('Validation error details:', {
        message: error.message,
        code: error.code
      });
    }
  }
};

Custom validation

Implement custom validation logic before allowing the Google Pay sheet to open.

const googlePayConfig = {
  onCustomValidation: async () => {
    const validations = [];
    
    // 1. Validate email
    const email = document.getElementById('email')?.value;
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      validations.push('Please enter a valid email address');
    }
    
    // 2. Validate terms acceptance
    const termsAccepted = document.getElementById('terms')?.checked;
    if (!termsAccepted) {
      validations.push('Please accept the terms and conditions');
    }
    
    // 3. Validate minimum order amount
    const orderTotal = getOrderTotal();
    const minimumOrderAmount = 10.00;
    if (orderTotal < minimumOrderAmount) {
      validations.push(`Minimum order amount is $${minimumOrderAmount.toFixed(2)}`);
    }
    
    // 4. Validate inventory availability
    try {
      const inventoryCheck = await checkInventoryAvailability();
      if (!inventoryCheck.allAvailable) {
        validations.push('Some items in your cart are no longer available');
      }
    } catch (error) {
      validations.push('Unable to verify inventory. Please try again.');
    }
    
    // 5. Validate customer eligibility
    const customerEligible = await checkCustomerEligibility();
    if (!customerEligible) {
      validations.push('Google Pay is not available for your account');
    }
    
    // Show errors if any
    if (validations.length > 0) {
      showValidationErrors(validations);
      return false; // Prevent payment sheet from opening
    }
    
    return true; // All validations passed
  }
};

function showValidationErrors(errors) {
  const errorContainer = document.getElementById('validation-errors');
  errorContainer.innerHTML = `
    <div class="error-message">
      <h4>Please fix the following errors:</h4>
      <ul>
        ${errors.map(error => `<li>${error}</li>`).join('')}
      </ul>
    </div>
  `;
  errorContainer.style.display = 'block';
  
  // Scroll to errors
  errorContainer.scrollIntoView({ behavior: 'smooth', block: 'center' });
}