Reputation: 157
I am trying to validate my input field by checking if a string is a proper number with comma and period and if yes get the value
I tried two functions both not working as expected:
function isNumeric(str) {
console.log(parseFloat(str.replace(/,/g,'')))
return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
!isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}
const isValidNumber = (str) => {
console.log(parseFloat(str.replace(/,/g,'')))
// return /^[0-9,.]*$/.test(str);
return /^\d{0,4}(?:[.,]\d{1,3})?$/.test(str)
// return /^[0-9,]?.[0-9]/.test(str);
// return /([0-9,.]+)$/.test(str)
}
the test cases I prepared
console.log(isNumeric("2"))//true
console.log(isNumeric("2,00,000"))//true
console.log(isNumeric("2,7,5,.34"))//false
console.log(isNumeric("2,450,0000.22.22"))//false
console.log(isNumeric("2q,3,4"))//false
But it's not working as intended, I need a regex to fix this. Also need to check if parseFloat(str.replace(/,/g,''))
is the right way to extract value
Upvotes: 0
Views: 378
Reputation: 522302
Here is a general regex pattern for matching a number with proper thousands separator and an optional decimal component:
\d{1,3}(?:,\d{3})*(?:\.\d+)?
function isNumeric(input) {
return /^\d{1,3}(?:,\d{3})*(?:\.\d+)?$/.test(input);
}
console.log(isNumeric("2")); // true
console.log(isNumeric("2,000,000")); // true
console.log(isNumeric("3.14159")); // true
console.log(isNumeric("2,7,5,.34")); // false
console.log(isNumeric("2,450,0000.22.22")); // false
console.log(isNumeric("2q,3,4")); // false
Upvotes: 1