Created
January 1, 2022 07:49
-
-
Save Sandip124/0a01e84dfdf56f68524b323670ee8f4d to your computer and use it in GitHub Desktop.
A simple number validator function in JS to validate numeric inputs
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
function validateNumericBox(elm){ | |
$(elm).on('keyup', (e)=>{ | |
e.preventDefault() | |
let rate = $(elm).val() | |
if(!isNormalInteger(rate)){ | |
$(elm).val(0); | |
}else{ | |
$(elm).val(rate.replace(/^0+/, "")); | |
} | |
}); | |
} | |
function validateDecimalBox(elm){ | |
$(elm).on('keyup', (e)=>{ | |
e.preventDefault() | |
let rate = $(elm).val() | |
if(!isNormalFloat(rate)){ | |
$(elm).val(0); | |
}else{ | |
$(elm).val(rate.replace(/^0+/, "")); | |
} | |
}); | |
} | |
function isNormalInteger(str) { | |
str = str.trim(); | |
if (!str) return false; | |
str = str.replace(/^0+/, "") || "0"; | |
const n = Math.floor(Number(str)); | |
return n !== Infinity && String(n) === str && n >= 0; | |
} | |
function isNormalFloat(input) { | |
let RE = /^-{0,1}\d*\.{0,1}\d+$/; | |
return (RE.test(input)); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment