Reputation: 751
I'm trying to make a validation that must accept the decimal numbers with up to 3 fields. The comma can only appear if you have at least one number entered
Allow:
100,000
1,0
1
1,00
Doesn't Allow:
,00
,150
,0
100 100
I tried it (I'm using React
to get the input value):
var code = (event.which) ? event.which : event.keyCode;
if (code !== 46 && (code < 48 || code > 57)) {
event.preventDefault();
}
So far, I have managed to limit only fields and the point. But, it still allows .000
and is not limited to 3 decimal places.
How can I do this?
-------------- UPDATE SOLUTION --------------
I found this answer that solve my problem. Thank you so much for your help guys
Upvotes: 0
Views: 1126
Reputation: 1047
I am not sure I understood your question well (I can update my solution based on your input) but I think you need a regular expression to match your overall value, not the individual inputs:
function is_valid(value) {
var exp = /^\d+(,*\d+)?$/;
return exp.test(value)
}
tests = ["100,000", "1,0", "1", "1,00", ",00", ",150", ",0", "100 100"]
for(var i=0; i<tests.length; i++) {
console.log(tests[i], is_valid(tests[i]))
}
Upvotes: 1