JSFiddle - React, Tailwind, and code Playground
JavaScript
function validateDecimal(num) {
//goal: decimal number, only one [.,] allowed, only 2 digits after [.,]
//first we check for invalid numbers
var findInvalid = num.match(/[^0-9\,\.]/g);
if(findInvalid) //found invalid chars
return false;
//now replace , to . (dot is more machinelike)
var num = num.replace(/,/g,".");
//now find number of occurences of .
var count = (num.match(/\./g) || []).length;
if(count > 1)
return false; //we have more than one . -> so its invalid
//now we count the chars after the first .
var indexOfDot = num.indexOf(".");
if(indexOfDot == -1)
return true; //we have no dot - so its pure numeric (no decimal)
var charsAfterDot = num.length - (indexOfDot+1);
if(charsAfterDot > 2)
return false; //we have more than 2 chars after dot - invalid
return true; //every other case is valid
}
validateDecimal("1a");
validateDecimal("2,22");
validateDecimal("3.333");
validateDecimal("4,44,111");
validateDecimal("555555");