Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
1.00/5 (1 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
Comments
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
Sergey Alexandrovich Kryukov 8-Jun-12 10:31am    
"Not working" is not descriptive. What's the problem? Do you have a code sample to manifest the problem?
--SA
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
}
else
{
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?

Use regular expression:

C#
string num = "0.7";

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

if (pattern.Match(num).Success)
{
    Console.WriteLine("OK");
}


The above code will validate decimal numbers greater than 0 and less than 1, upto 3 decimal places.
 
Share this answer
 
Comments
Maciej Los 8-Jun-12 11:03am    
Good answer, my 5!
Manas Bhardwaj 8-Jun-12 11:12am    
Thanks!
IamBlessed 8-Jun-12 11:25am    
Thanks for the answer
Easier just to prevent any but numeric keys in the KeyPress event for the textbox. This is how you do it in WinForms:

C#
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 http://msdn.microsoft.com/en-us/library/h62wtc8c.aspx[^]
 
Share this answer
 
v2
Comments
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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900