简体   繁体   中英

Regular expression for two decimal places not working in JavaScript. Am I missing something?

I am using a regular expression to validate input from a text field to only allow a whole number or a number with up to two decimal places (eg: 10, 10.4, 10.45, 100.45) ,however when I enter a number with 3 or more decimal places it will still validate it. Code shown below.

var loanAmount = document.getElementById("loan_amount");

var loanRE = /\d+(\.\d{1,2})?/;

if (!(loanRE.test(loanAmount.value))){
alert("Not a valid input for the loan amount");
return false;
}

Everything looks good to me. What am I missing?

Anchor your regex. loadRE = /^\\d+(\\.\\d{1,2})?$/

Otherwise it will just say "okay, there's some digits. It passes!"

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