/** * Project: CaribMedia javascript library * File: cm.string.js * * @link http://www.visitaruba.com/plus * @copyright 2008 CaribMedia * @author Michiel van der Blonk * @package Types */ /* * @Date: Feb 21, 2005 * @Description: This function strips defined chars from a string * useful in validation routines * example: str.stripChars("()-") returns the string with any * brackets and dashes removed **/ String.prototype.stripChars = function(chars) { var i; var newstring = ""; for (i = 0; i < this.length; i++) { var mychar = this.charAt(i); if (chars.indexOf(mychar) == -1) newstring += mychar; } return newstring; }; /** * @Date: Feb 21, 2005 * @Description: This function extracts defined chars from a string * useful in validation routines * it is 'sort of' the reverse of stripChars * example: str.extractChars("0123456789") returns all digits from the string **/ String.prototype.extractChars = function(chars) { var i; var newstring = ""; for (i = 0; i < this.length; i++) { var mychar = this.charAt(i); if (chars.indexOf(mychar) != -1) newstring += mychar; } return newstring; }; /** * @Date: Dec 1, 2004 * @Description: This function tests a credit card using the Luhn validation * The sum of digits must be divisible by 10 * digits in odd positions are doubled, then sum of left+right digit is taken **/ String.prototype.isValidCreditCard = function() { var nTotal = 0; var nPosition = 0; var bValid = true; // innocent until proven guilty var sCreditCardNumber = this.extractChars("0123456789"); if (sCreditCardNumber.length < 13) bValid = false; else { for ( var i = sCreditCardNumber.length; i > 0 ; i--) { var nDigit = 0; // advance nPosition++; // get digit nDigit= parseInt(sCreditCardNumber.charAt(i-1)); // odd position: add to total if ((nPosition % 2) !== 0) nTotal += parseInt(nDigit); else // even position: add sum of digits to total { // calc sum of left and right digit (use parseInt to cut off fractional parts var nDoubled = nDigit * 2; var nLeftDigit = parseInt(nDoubled / 10); var nRightDigit = nDoubled % 10; // get sum of left and right nTotal += nLeftDigit + nRightDigit; } } // if divisible by 10 it is valid bValid = (nTotal % 10) === 0; } return (bValid); }; /* check if d is a date value * formatted means it is in fact a string, formatted as mm/dd/yyyy * dates like 44/55/2000 are invalid, even though to JavaScript * these _are_ valid */ String.prototype.isDate = function(formatted) { var ret = false; var val = this.toString(); var date = new Date(val); // it's at least a number if (!isNaN(date)) { if (formatted) { if (window.console) console.assert(typeof Date.prototype.format == 'function'); var pattern = new RegExp(date.format(null, '.', true)); // . means you can use e.g. '-' or '/' ret = pattern.test(val); } else ret = true; } return ret; };