Skip to content

Instantly share code, notes, and snippets.

@mcwhittemore
Last active December 17, 2015 02:09
Show Gist options
  • Save mcwhittemore/5533782 to your computer and use it in GitHub Desktop.
Save mcwhittemore/5533782 to your computer and use it in GitHub Desktop.
Javascript Validators and Formatters
//FROM: http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript
Number.prototype.formatMoney = function(c, d, t){
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
(8888.888).format(2, '.', ','); //8,888.88
//FROM: http://stackoverflow.com/questions/46155/validate-email-address-in-javascript
var validEmailAddress = function (email_address) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email_address);
}
//FROM: http://stackoverflow.com/questions/4338267/validate-phone-number-with-javascript
var validPhoneNumber = function(phone_number){
return /^(\()?[2-9]{1}\d{2}(\))?(-|\s)?[2-9]{1}\d{2}(-|\s)?\d{4}$/.test(phone_number);
}
//FROM: http://stackoverflow.com/questions/160550/zip-code-us-postal-code-validation
var validZipCode = function (zip_code) {
return /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(zip_code);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment