Skip to content

Instantly share code, notes, and snippets.

@itzikbenh
Last active December 22, 2016 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save itzikbenh/a3e531f5b6e3be9ffdfc55010b654f3a to your computer and use it in GitHub Desktop.
Save itzikbenh/a3e531f5b6e3be9ffdfc55010b654f3a to your computer and use it in GitHub Desktop.
Validate floats and ints in JavaScript
//Removes all dots after the first one.
function removeExtraDots(str) {
return str.replace( /^([^.]*\.)(.*)$/, function ( a, b, c ) {
return b + c.replace( /\./g, '' );
});
}
function dotsCount(number) {
return (number.match(/[.]/g) || []).length;
}
//Checks if pattern matches float
function matchFloat(number) {
var match = /^[0-9.]+$/.test(number);
if(match && (dotsCount(number) <= 1)) {
return true;
}
return false;
}
//Numbers and dots only
function ensureFloat(selector) {
var number = selector.val();
if(!matchFloat(number)) {
number = number.replace(/[^0-9.]/g, "");
if(dotsCount(number) > 1) {
number = removeExtraDots(number);
}
selector.val(number);
}
}
function matchInt(number) {
var match = /^[0-9]+$/.test(number);
if(match) {
return true;
}
return false;
}
//Only numbers
function ensureInt(selector) {
var number = selector.val();
if(!matchInt(number)) {
number = number.replace(/[^0-9]/g, "");
selector.val(number);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment