tags:

views:

113

answers:

6

I want to enter only digits in a textbox with the following condition

  • maximum 3 digits
  • maximum from 0 to 250..so 251 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)
+3  A: 

You don't need regex for that.

var val = parseInt($(this).val(), 10);
alert(val >= 0 && val < 250);
Reinis I.
Don't forget to specify a radix for `parseInt`
Josh Stodola
I guess you're right, thanks.
Reinis I.
The radix is optional, so its not strictly required. ParseInt will try to determine which base to use. However, specifying it avoids getting unexpected results when someone enters numbers starting with 0.
Andre Miller
@Andre: not just unexpected... I've seen very serious bugs and security holes due to that mistake (it was server-side javascript).
rmeador
As a general rule of thumb, you should *always* specify a radix. Trust me on this.
Josh Stodola
+2  A: 
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;
}
Josh Stodola
+1  A: 
Rubens Farias
+1  A: 

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
}
Neil Aitken
You'd have to be careful here to make sure that you parse the value as an integer, as a user could enter something that's not a number.
S Pangborn
+1  A: 

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.

iammichael
+1  A: 

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).

jlech