How to enter digits to a certain number
I want to enter only digits in a textbox with the following condition
- maximum 3 digits
- maximum from 0 to 250..so 2开发者_C百科51 should not be accepted.
I have written the following code till now..how to take the other conditions too
this.value.match(/[^0-9]/g)
You don't need regex for that.
var val = parseInt($(this).val(), 10);
alert(val >= 0 && val < 250);
var val = parseInt(this.value, 10);
if(isNaN(val)) {
alert("Invalid amount: " + val);
this.select();
return false;
}
if(val < 0 || val > 250) {
alert("Amount can range from 0 to 250");
this.select();
return false;
}
try this
var intVal = parseInt(this.value,10);
if( intVal > 0 && intVal < 250)
// ...
this.value.match(/[^0-9]{1,3}/g)
will give you 1 to 3 digits, but a regex is probably the wrong way to go about it as you will need to your bounds checking after the regex anyway.
It would probably be better to use something like
if(this.value < 0 || this.value > 250) {
// foo
}
If you really want a regex (though, as mentioned, other options are probably more appropriate), here is one that will match 0-250:
/^([01]?[0-9]{1,2}|2([0-4][0-9]|50))$/
Breaking this down, we use the |
operator to match either:
[01]?[0-9]{1,2}
Or
2([0-4][0-9]|50)
The first part matches 0 (or 00 or 000) through 199. The second part uses a similar scheme to match 200 through 249 or 250.
Regex is complete overkill for this. You can use javascript to validate this on the client side.
If you happen to be doing this in ASP.NET, you can use the Range Validator control to ensure that the user only enters integers from 0 to 250 (or whichever min and max values you want).
精彩评论