Last active
December 22, 2016 21:53
-
-
Save itzikbenh/a3e531f5b6e3be9ffdfc55010b654f3a to your computer and use it in GitHub Desktop.
Validate floats and ints in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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