简体   繁体   中英

JavaScript regular expression 5-5000

I know that this:

var regStartMoney = /[1-5][0-9][0-9][0-9]/;

allows you to enter from 1-5999.

how do I do it for a range of 5-5000?

Regex misuse! Just do it the sane way:

var int = parseInt(input,10);
if (isNan(input)) {
    alert('Please enter a number.');
} else if (input != int) {
    alert('Decimals are not allowed.');
} else if (!(int >= 5 && int <= 5000)) {
    alert('Your number must be between 5 and 5000 (inclusive).');
} else {
    alert('Your number is valid!');
}
var regStartMoney = /^0*(?:[5-9]|[1-9][0-9][0-9]?|[1-4][0-9][0-9][0-9]|5000)$/;

Why not just:

var money = parseInt(input);
var test = Math.min(Math.max(money, 5), 5000);

if(money !== test) //

You should really convert to a number and compare. But that wasn't your question so here's your answer:

var regStartMoney = /^0*([5-9]|([1-9]\d{0,2})|([1-4]\d{3})|(50{3}))$/;

Here's a test script:

<script>
function checkMoney() {
  var money=document.getElementById("money").value;
  if (money.match(/^0*([5-9]|([1-9]\d{0,2})|([1-4]\d{3})|(50{3}))$/)) {
    alert(money+" is between 5-5000");
  } else {
    alert(money+" is not between 5-5000");
  }
}
</script>
<input id="money"/></br>
<input type="submit" onClick="checkMoney();"/><br/>

Test on jsfiddle

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