Skip to content

Instantly share code, notes, and snippets.

@Sandip124
Created January 1, 2022 07:49
Show Gist options
  • Save Sandip124/0a01e84dfdf56f68524b323670ee8f4d to your computer and use it in GitHub Desktop.
Save Sandip124/0a01e84dfdf56f68524b323670ee8f4d to your computer and use it in GitHub Desktop.
A simple number validator function in JS to validate numeric inputs
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