As the title says, I need to validate that the number entered in an input is suitable for a percentage. I'm trying to do it with a regular expression but so far I can't get it to work correctly. For example, when entering numbers without decimals, it tells me that it is incorrect, when it would be a valid value for a percentage.
Values that I consider allowed:
- Matches 100, 100.0 and 100.00
- Numbers like 0, 15, 99, 3.1, 21.67
,
, letters or any other type of characters should NOT be allowed . Just numbers and a dot. Only precision of 2 decimal places maximum.
The regular expression that I managed to build and am using is:
(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)
Here is a small example of the code:
function checkValue(){
var strporc = document.getElementById("txt_porcentaje").value
var isValid = strporc.match(/^(100(\.0{1,2})?|([0-9]?[0-9](\.[0-9]{1,2})))$/) == null ? false:true;
console.log("Permitido: "+isValid);
}
<label for="txt_porcentaje">Porcentaje:</label>
<input type="text" id="txt_porcentaje" oninput="checkValue();">
In advance thanks for the help!
Here is the working code:
I hope it helps you.
Luck!