Javascript Numeric Validation
Join the DZone community and get the full member experience.
Join For FreeI've seen a lot of takes on numeric validation, and most have serious flaws. For example, (!isNaN) returns inconsistent results and shouldn't be used to verify numericality. This should cover all cases, and supports a decimal point as well as negative numbers.
function isNumeric(value) {
if (value == null || !value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
return true;
}
This logic is straight-forward: if the parameter isn't null, convert it to a string and match it against a RegEx to throw out false cases. Otherwise, return true.
JavaScript
Opinions expressed by DZone contributors are their own.
Comments