How to validate Google Analytics tracking id using a JavaScript function

Viewed 3574

I need to validate a Google Analytics tracking ID. So I created a simple function but my RegEx must be wrong because it just returns false everytime. I'm not sure if there is a set amount of digits in the middle or at that end of a Google Analytics ID so was just trying to just look for at least one digit.

JavaScript Function:

function validateGA(id) {
    var regexp = /ua-\d+-\w\d+/;
    return regexp.test(id);
}

Tested with validateGA('UA-12345-12'); but just keep returning false.

JSFiddle: http://jsfiddle.net/g9yLr/

5 Answers

GA ID does not have a fixed number of digits in it. Also, There have been legacy ids that started with MO or YT etc. For your purposes, the correct regex could be something like:

/(UA|YT|MO)-\d+-\d+/i.test(id)

This works for following scenarios:

UA-1234-12
YT-1234-12
MO-1-1
UA-1234-1
ua-1-1
UA-1234- // Invalid
UA--1   // Invalid

Also, To check this in jsfiddle: http://jsfiddle.net/c4mkH/1/

@Avi's answer is pretty close, but it will fail in the following cases:

test-UA-1234-12
UA-1234-12-test

So, the Javascript function with the correct regex is:

function validateGAId(id) {
  return /^(UA|YT|MO)-\d+-\d+$/i.test(id);
}

I wanted to also mention that the newest version of Google Analytics allows letters in the second part of the Tracking ID - for instance, this is now valid:

G-2RJ8P0I4GC

This is the regex I ended up using:

^(G|UA|YT|MO)-[a-zA-Z0-9-]+$

Don't know JS but it needs to be case insensitive to match the UA

either /(?i)ua-\d+-\w\d+/ or /ua-\d+-\w\d+/i

Related