Click here to Skip to main content
12,948,385 members (70,996 online)
Rate this:
Please Sign up or sign in to vote.
See more:
Hi guys i am trying to validate a textbox to accecpt only numbers within a specified range, but it is not working, any idea what to do.. Thanks in advance
Posted 8-Jun-12 4:07am
Manas Bhardwaj 8-Jun-12 10:16am
What kind of code you are using?
IamBlessed 8-Jun-12 10:29am
I have tried using the NumericUpDown class, but it is not working since my values are decimal, i also tried using int32.parse(mytextbox) then use a if statement to check it agaisnt the range. But still did not work, the Range are 0.01 - 0.90
SAKryukov 8-Jun-12 10:31am
"Not working" is not descriptive. What's the problem? Do you have a code sample to manifest the problem?
IamBlessed 8-Jun-12 10:34am
int val = 0;
bool res = Int32.TryParse(Ca_TxtBx.Text, out val);
if (res == true && val > 0.01 && val < 0.90)
// Do something
MessageBox.Show("Please input 0.01 to 0.90 only.");

and this

NumericUpDown control = new NumericUpDown();

decimal max = Convert.ToDecimal(0.90);
decimal min = Convert.ToDecimal(0.01);

control.Minimum = min;
control.Maximum = max;

if (Convert.ToDecimal(Ca_TxtBx.Text) > control.Maximum || Convert.ToDecimal(Ca_TxtBx.Text) < control.Minimum)
MessageBox.Show("Please input 0.01 to 0.90 only.");


it does not validate the texbox..
Clifford Nelson 8-Jun-12 12:13pm
Are you doing winforms or WPF?
IamBlessed 8-Jun-12 15:30pm
Window form
Clifford Nelson 8-Jun-12 16:17pm
So what do you think of limiting only to number keys?
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Use regular expression:

string num = "0.7";
Regex pattern = new Regex(@"^[0]+(.[0-9]{1,2})?$");
if (pattern.Match(num).Success)

The above code will validate decimal numbers greater than 0 and less than 1, upto 3 decimal places.
losmac 8-Jun-12 11:03am
Good answer, my 5!
Manas Bhardwaj 8-Jun-12 11:12am
IamBlessed 8-Jun-12 11:25am
Thanks for the answer
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

Easier just to prevent any but numeric keys in the KeyPress event for the textbox. This is how you do it in WinForms:

private void KeyPress(object sender, KeyPressEventArgs e)
    if (!char.IsDigit(e.KeyChar))
        e.Handled = true;

May want to do a beep or something when an non-digit key is pressed: See[^]
IamBlessed 8-Jun-12 16:21pm
Thanks For your answer this has been very useful

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    Print Answers RSS
Top Experts
Last 24hrsThis month
OriginalGriff 5,344
CHill60 3,275
Maciej Los 2,703
Jochen Arndt 1,935
ppolymorphe 1,795

Advertise | Privacy | Mobile
Web01 | 2.8.170524.1 | Last Updated 8 Jun 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100