I'm creating a form on my website for donations I want to have the donation field to be a text box with the value of any amount of money between 5 to 500 and for an other currency to be between 2000 and 200000 please help.
问题:
回答1:
Do not use regular expression here
there are too many ways to check ie x
is in a range. Regular expression will cause performance problem here.
here is the actual answer
regex for range 5 to 500:
/^(?:[5-9]|(?:[1-9][0-9])|(?:[1-4][0-9][0-9])|(?:500))$/
edit^2
I do not know why regex is important here. But i will explain how it works.
As regex is a pattern matching language, we can only match pattern with it. So, we have to find some pattern in it.
Here the patterns are: 5-9 or 10-99 or 100-499 and 500.
So if our regex is /[5-9]/
it will match our first one. Thus /[1-9][0-9]/
, /[1-4][0-9][0-9]/
and /500/
came.
But, should i validate our data multiple time?
No, you have another option.
We will use pipe for alternation check.
/[5-9]|([1-9][0-9])|([1-4][0-9][0-9])|(500)/
actually this should also work fine but i make them non capuring. So i put ?:
回答2:
You can use a regex for this, but keep in mind whether or not in 6 months you'll remember how this works.
^(500|[1-4][0-9][0-9]|[1-9][0-9]|[5-9])$
Your other values would function similarly: Start at the upper bound and specify it literally; then work down to your lower bound, specifying it literally (or in this case via a character class). Each change in the number of digits (e.g. 100 => 99) will require a new alternation.
回答3:
You don't need to use regex here. Just capture the value of your form input and then compare that against your number range. This is a very common task in JavaScript and is known as "form validation."
http://jsbin.com/ihoxut/2/edit
document.forms["myform"].onsubmit = function () {
var donationAmount = document.getElementById('donation').value;
if (donationAmount > 500) {
alert("Too high!");
return false;
} else if (donationAmount < 5) {
alert("Too low!");
return false;
} else {
alert("Just right!");
return false;
// You would actually want to return true for this one to submit the form, but that would break jsbin
}
};
回答4:
Don't use regex for it.
if you use php do:
if (($currency == $currency1) && ($amount >= 5) && ($amount <= 500)) {
echo "Between 5 and 500 at currency 1";
} elseif (($currency == $currency2) && ($amount >= 2000) && ($amount <= 200000)) {
echo "Between 2000 and 200000 at currency 2";
} else {
echo "Not a valid amount";
}
of course you could do similar in java on clientside or any other language you want to use