I try to validate various input strings. Therefore I tried to use regular expressions. Unfortunately all negativ cases match to true as well. How can I sepcify that the regular expression has to match the whole string?
const regex = /(^([0-9]+(.||,)+[0-9]?)$)||(^([0-9]+)$)||(^(.||,)+[0-9]+$)/;
const testSetPositiv = ["34", "45.45", ".7867", "3434,34", ",7834", "546.", "45546,", "0"]
const testSetNegativ = ["wegrger", "3443,34erf", "3443.34erf", ",", ".", "4525tg", "1,211.23", "1.211,23"]
testSetPositiv.forEach(function(value) {
console.log(regex.test(value));
//should always return true
})
console.log("----------------");
testSetNegativ.forEach(function(value) {
console.log(regex.test(value));
//should always return false
})
I also tried to use parseFloat(...), but it accepts for example "5.45abc":
const testSetPositiv = ["34", "45.45", ".7867", "3434,34", ",7834", "546.", "45546,", "0"]
const testSetNegativ = ["wegrger", "3443,34erf", "3443.34erf", ",", ".", "4525tg", "1,211.23", "1.211,23"]
testSetPositiv.forEach(function(value) {
console.log(parseFloat(value) >= -Number.MAX_VALUE)
//should always return true
})
console.log("----------------");
testSetNegativ.forEach(function(value) {
console.log(parseFloat(value) >= -Number.MAX_VALUE)
//should always return false
})