Random Custom Serial Number Generator

A brief example on how to generate random serial numbers with JavaScript. Enjoy!



// Symbols Array (A-Z, 0-9)

var Symbols = new Array();

// Gets the ascii code for a certain character

function GetAsciiBySymbol(letter)

{

var code = letter.charCodeAt(0);

return code;

}

// Populates a certain array with the A-Z, 0-9 symbols

function PopulateArray(array) {

var Position = 0;

// Letters

for(i=GetAsciiBySymbol(‘A’); i<=GetAsciiBySymbol('Z'); i++) {


array[Position] = String.fromCharCode(i);

Position++;

}



// Numbers

for(i=GetAsciiBySymbol(‘0’); i<=GetAsciiBySymbol('9'); i++) {

array[Position] = String.fromCharCode(i);

Position++;

}



}



// Gets the array symbol by a certain index

function GetSymbol(index) {

return Symbols[index];

}



// Generates a new Serial Number

function GenerateSerial(serialLength, separatorSymbol, separatorPositions) {

var serial = “”;

var Offset = 0;



for(i=0; i

var rnd = Math.floor(Math.random()*Symbols.length);

serial += GetSymbol(rnd);

}



if(SeparatorPositionsOk(separatorPositions,serialLength)) {

for(i=0; i

var position = separatorPositions[i];

serial = serial.substring(0,position + Offset) + separatorSymbol + serial.substring(position + Offset, serial.length); Offset++;

}

}



return serial;

}

// Checks if a certain array contains only items less than a maximum value

function SeparatorPositionsOk(array, maxValue) {

for(i=0; i maxValue) {

return false;

}

}

return true;

}

// Populate Symbols

PopulateArray(Symbols);

// Example 1 – Format: XXXXX-XXXXX-XXXXX-XXXXX-XXXXX

var SepPos = new Array();

SepPos[0] = 5;

SepPos[1] = 10;

SepPos[2] = 15;

SepPos[3] = 20;

var NewSerial = GenerateSerial(25, “-“,SepPos);

alert(“Serial Number: ” + NewSerial);

// Example 2 – Format: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX

SepPos = new Array();

SepPos[0] = 8;

SepPos[1] = 12;

SepPos[2] = 16;

SepPos[3] = 20;

SepPos[4] = 24;

NewSerial = GenerateSerial(32, “-“,SepPos);

alert(“Serial Number: ” + NewSerial);

// Example 3 – Format: XXX-XXXXXXX

SepPos = new Array();

SepPos[0] = 3;

NewSerial = GenerateSerial(10, “-“,SepPos);

alert(“Serial Number: ” + NewSerial);


Leave a comment

Your email address will not be published. Required fields are marked *