views:

1490

answers:

4

In asp.net, I need to add a validator to a textbox that forces the input to be numbers.

Is this built in?

I have already added a required field validator to the textbox.

+5  A: 

You could use a Regex Validator to ensure the text is numeric

I think the regex would be

[0-9]*

e.g.

<asp:TextBox ID="tbxNumbers" runat="server" />
<asp:RegularExpressionValidator ID="revNumericValidator" runat="server" 
                ValidationExpression="^[0-9]*$" ControlToValidate="tbxNumbers" ErrorMessage="Must be Numeric" />

EDIT: As the other two posters also pointed out you can also use \d to represent a Numeric Character

Eoin Campbell
\d+ might be better
Keltex
Note that + rather than the * also makes the required field validator redundant.
Joel Coehoorn
I like regex, but think it is overkill in this case; a range validator would be more "efficient", since you could easily permit decimals and so on, depending on the Type attribute you use.
Cyberherbalist
@Joel Coehoorn... I'm fairly sure it doesn't. A + means 1 or More characters however the example i gave there with a simple button click will validate on an empty textbox. I think the regex validator only kicks in for a .Text Length > 1
Eoin Campbell
blasphemous answer acceptance ;)
Eoin Campbell
+3  A: 
<asp:RegularExpressionValidator runat="server"
            ControlToValidate="numbersOnlyTextBox" 
            ErrorMessage="Enter only numeric characters." 
            ValidationExpression="^\\d+$" />
Chris Ballance
ValidationExpression="^\\d*$"
Tracker1
Thanks, It actually should be + instead of * since there is a requirement for it to be non-empty.
Chris Ballance
+2  A: 

Use a range validator.

<asp:TextBox ID="MyTextBox" MaxLength="4" Width="75" 
   Text="0" runat="server"></asp:TextBox>
<asp:RangeValidator ID="MyRangeValidator"  Display="Static" Type="Integer"
   MaximumValue="9999" MinimumValue="0" EnableClientScript="true" 
   ControlToValidate="MyTextBox" runat="server" SetFocusOnError="true" 
   ErrorMessage="Ooops"></asp:RangeValidator>

This permits you to use numbers with decimal places (by using Type="Double" or "Currency"), or other kinds of numbers that Windows recognizes.

Check MSDN for more info on the Range Validator Control.

Cyberherbalist
A: 

I think there needs to be more clarification of the requirements here. What kind of numbers are we talking about? Positive integers? Any integer? A number with a decimal place? What about commas in the number (1,000)?

I recommend a RegularExpressionValidator to do your work, but these questions make a difference when it comes to which RegEx you use.

Brandon Montgomery