How to validate Google Analytics tracking id using a JavaScript function
Categories:
Validate Google Analytics Tracking IDs with JavaScript and Regex
Learn how to effectively validate Google Analytics tracking IDs (UA- and G-) using robust JavaScript functions and regular expressions, ensuring data integrity and correct implementation.
Google Analytics tracking IDs are crucial for collecting website data. Incorrectly formatted IDs can lead to tracking failures, data loss, and inaccurate reports. This article provides a comprehensive guide on how to validate both Universal Analytics (UA-) and Google Analytics 4 (G-) tracking IDs using JavaScript and regular expressions. We'll explore the structure of these IDs, develop a flexible validation function, and discuss best practices for implementation.
Understanding Google Analytics Tracking ID Formats
Before we can validate, we need to understand the expected format of Google Analytics tracking IDs. There are two primary types you'll encounter:
- Universal Analytics (UA- IDs): These typically follow the pattern
UA-XXXXX-Y
orUA-XXXXX-YY
, whereX
represents digits for the account number andY
orYY
represents digits for the property number. The account number usually has 5 to 9 digits, and the property number has 1 or 2 digits. - Google Analytics 4 (G- IDs): These are a newer format, generally structured as
G-XXXXXXXXXX
, whereX
represents 10 alphanumeric characters (digits or uppercase letters). These IDs are more consistent in length.
flowchart TD A[Start Validation] --> B{Is ID provided?} B -- No --> C[Invalid: Empty ID] B -- Yes --> D{Matches UA- regex?} D -- Yes --> E[Valid: UA- ID] D -- No --> F{Matches G- regex?} F -- Yes --> G[Valid: G- ID] F -- No --> H[Invalid: Unknown Format] C,E,G,H --> I[End Validation]
Flowchart of Google Analytics ID Validation Logic
Crafting Regular Expressions for Validation
Regular expressions (regex) are powerful tools for pattern matching. We'll need two distinct regex patterns to cover both UA- and G- ID formats. It's important to make these patterns robust enough to catch common variations while being strict enough to reject invalid inputs.
const uaRegex = /^UA-\d{4,9}-\d{1,2}$/;
const gRegex = /^G-[A-Z0-9]{10}$/;
// Example usage:
console.log(uaRegex.test('UA-12345-1')); // true
console.log(uaRegex.test('UA-123456789-99')); // true
console.log(uaRegex.test('UA-123-1')); // false (too few digits)
console.log(gRegex.test('G-ABCDEFGHIJ')); // true
console.log(gRegex.test('G-1234567890')); // true
console.log(gRegex.test('G-abcdefghij')); // false (lowercase)
console.log(gRegex.test('G-12345')); // false (too few characters))
^
and $
anchors in the regex are crucial. They ensure that the entire string must match the pattern, preventing partial matches that could lead to false positives.Implementing a Universal Validation Function
Now, let's combine these regex patterns into a single, reusable JavaScript function that can validate any given Google Analytics tracking ID. This function will return true
if the ID is valid according to either pattern, and false
otherwise.
/**
* Validates a Google Analytics tracking ID (UA- or G- format).
* @param {string} trackingId The Google Analytics tracking ID to validate.
* @returns {boolean} True if the ID is valid, false otherwise.
*/
function isValidGoogleAnalyticsId(trackingId) {
if (typeof trackingId !== 'string' || trackingId.trim() === '') {
return false; // Not a string or empty
}
const trimmedId = trackingId.trim();
// Regex for Universal Analytics (UA-XXXXX-Y or UA-XXXXX-YY)
// X: 4-9 digits, Y: 1-2 digits
const uaRegex = /^UA-\d{4,9}-\d{1,2}$/;
// Regex for Google Analytics 4 (G-XXXXXXXXXX)
// X: 10 alphanumeric characters (digits or uppercase letters)
const gRegex = /^G-[A-Z0-9]{10}$/;
return uaRegex.test(trimmedId) || gRegex.test(trimmedId);
}
// Test cases
console.log("UA-12345-1: " + isValidGoogleAnalyticsId('UA-12345-1')); // true
console.log("UA-987654321-99: " + isValidGoogleAnalyticsId('UA-987654321-99')); // true
console.log("G-ABCDEFGHIJ: " + isValidGoogleAnalyticsId('G-ABCDEFGHIJ')); // true
console.log("G-1234567890: " + isValidGoogleAnalyticsId('G-1234567890')); // true
console.log("UA-123-1: " + isValidGoogleAnalyticsId('UA-123-1')); // false (UA too short)
console.log("G-abcde: " + isValidGoogleAnalyticsId('G-abcde')); // false (G too short/lowercase)
console.log("Invalid-ID: " + isValidGoogleAnalyticsId('Invalid-ID')); // false
console.log("" : " + isValidGoogleAnalyticsId('')); // false
console.log("null: " + isValidGoogleAnalyticsId(null)); // false
console.log("undefined: " + isValidGoogleAnalyticsId(undefined)); // false
typeof trackingId !== 'string'
at the beginning of your function to handle non-string inputs gracefully, preventing potential runtime errors.Practical Applications and Best Practices
This validation function can be used in various scenarios:
- Form Validation: Ensure users enter correct tracking IDs in configuration forms.
- API Input Validation: Validate IDs received through APIs before processing.
- Configuration Checks: Verify tracking IDs loaded from environment variables or configuration files.
- Automated Testing: Include these checks in your test suite to prevent deployment of incorrect IDs.
Best Practices:
- Trim Whitespace: Always trim whitespace from user input before validation to avoid issues with leading/trailing spaces.
- Case Sensitivity: G- IDs are case-sensitive (uppercase letters only). Ensure your regex accounts for this.
- Error Handling: Provide clear feedback to users when an ID is invalid.
- Future-Proofing: While these regexes cover current formats, Google might introduce new ID formats in the future. Keep your validation logic updated.