Question :
Hello, my question is about a field validation for decimal value. If the value is less than 500.00 I show an error message, otherwise step to the second field, as soon as the person types the value, the mask is already added.
I’m using it this way:
function valid_simulation(form1) {
if(parseInt($("#selector").val()) < 500) {
alert("valor não é valido");
return false;
}
}
In this way I can validate a value less than 500.00, but if it is greater than 1,000.00 it shows the error message.
Answer :
The error is happening because in the javascript language the decimals are separated by .
and not ,
. So if you “parse” a string that contains a point for int, the number becomes a different integer, because in this case it ignores the comma:
parseInt("1.000,00"); //mostra 1
parseInt("10.000,00"); //mostra 10
parseInt("100.000,00"); //mostra 100
You need to remove the points to perform parseInt correctly.
parseInt("1.000,00".replace(".","")); // mostra 1000
parseInt("10.000,00".replace(".","")); // mostra 10000
parseInt("100.000,00".replace(".","")); // mostra 100000
In your code:
function valid_simulation(form1) {
if(parseInt($("#selector").val().toString().replace(".", "")) < 500) {
alert("valor não é valido");
return false;
}
}
josecarlos, “saves” a working variable without the dot and compares it. So you do not have to keep pulling and peeking.