PhearOfRayne PhearOfRayne - 11 days ago 6
Javascript Question

How to validate Google Analytics tracking id using a JavaScript function

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/

Avi Avi
Answer

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/