JavaScript Format Currency isCurrency Validator Function

JavaScript Format Currency isCurrency Validator Function

This function generally we required while integrating payment system to the website. There are various currencies are available. The below isCurrency function accepts one argument as string. If the string is in form of Currency it returns true or else the function returns false.

JavaScript Format Currency

function isCurrency(arg) {

// instantiate argument as a String (for String operations)
var str = new String(arg);

// control-related
var i;
var ch;
var len = str.length;
var offset = 0;
var position = 0;

// counters
var decimals = 0;
var commas = 0;
var dollarsigns = 0;

if (str.length >= 1) {
// Increment counts for commas, decimals, and dollar signs
for (i = 0; i < len; i++) {
ch = str.charAt(i);
if (!isNaN(ch)) {
continue;
} else if (ch == ".") {
decimals++;
continue;
} else if (ch == ",") {
commas++;
return false;
} else if (ch == "$") {
dollarsigns++;
return false;
} else {
return false;
}
}
// If more than 1 dollar sign, invalid
if (dollarsigns > 1) {
return false;
} else if (dollarsigns == 1) {
if (!(str.charAt(0) == "$")) {
return false;
}
}
// If more than 1 decimal, invalid
if (decimals > 1) {
return false;
// If exactly 1 decimal and in correct position, valid; otherwise, invalid
} else if (decimals == 1) {
ch = str.charAt(len - 3);
if (!(ch == ".")) {
return false;
}
}

if (commas >= 1) {

if (str.charAt(0) == ",") {
return false;
}
if (decimals == 1) {
if ((str.charAt(len - 1) == ",") || (str.charAt(len - 2) == ",")) {
return false;
}
offset = 3;
}
for (i = ((len - offset) - 1); i >= 0; i--) {
ch = str.charAt(i);

if (position != 3) {
if (ch == ",") {
return false;
}
position++;
} else {
if (!(ch == ",")) {
return false;
}
position = 0;
}
}
}
}
// Optimistically assume program flow gets this far . . . !
return true;
}