简体   繁体   中英

Validate input with only number and decimal after dot

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

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]))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM