Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to validate textbox value in decimal point tow digits keypress/textchange event so that user couldn't enter invalid value in textbox.
Accepted value.

-1
1
112.1
12345.00
-12434.00

Invalid value
-0.00
1234.12354
1.231
1.000

I am trying following but unable to get proper solution have Google also

C#
private void TextBox_KeyPress(object sender, KeyPressEventArgs e)
       {
           if (e.KeyChar == '\b')
               return;
           TextBox txtTemp = sender as TextBox;
           e.Handled = Regex.IsMatch(txtTemp.Text.Insert(txtTemp.SelectionStart, e.KeyChar.ToString()), @"\[0-9]+\.([0-9]{1,2})?");
       }


Please help.

Thanks
Posted
Comments
Sinisa Hajnal 30-Jan-15 7:31am    
Simple :) Don't use keypress, keydown or whatever...validate the textbox once the user finishes the entry - validate on blur event (that is, lost focus)
Nathan Minier 30-Jan-15 7:42am    
This. Also, you're performing a regex against a character that includes a literal period. You'll never match against it.
MuhammadUSman1 30-Jan-15 22:28pm    
Thanks for reply.
Please tell me proper regex expression for my Question. I am new about Regex and its Expression and usage.
MuhammadUSman1 30-Jan-15 22:27pm    
Dear Sinisa First thanks for Suggestions and help.
but my requirement is something like this that user should not be able to enter any invalid character in textbox/winform. That's why i am using key events so that i prevent user from entering invalid values.

Please suggest any thing that handle this.

Thanks
Kenneth Haugland 30-Jan-15 7:52am    
Dim Real As String = "(?<!([E][+-][0-9]+))([-]?\d+\.?\d*([E][+-]" & _
"[0-9]+)?(?!([i0-9.E]))|[-]?\d*\.?\d+([E][+-][0-9]+)?)(?![i0-9.E])"
should work.

If your inclined to use the KeyPress event, simply use the int.TryParse rather than Regex..

This will allow the check on every key press and simpler. Not entirely sure if its more efficient than Regex.IsMatch but more readable for sure..

C#
private void TextBox_KeyPress(object sender, KeyPressEventArgs e)
        {           
            if (e.KeyChar == '\b')
                return;
            TextBox txtTemp = sender as TextBox;
            decimal number = 0;
            e.Handled = decimal.TryParse(txtTemp.Text, out number);
            //Regex.IsMatch(txtTemp.Text.Insert(txtTemp.SelectionStart, e.KeyChar.ToString()), @"\[0-9]+\.([0-9]{1,2})?");
        }


However if you NEED to use Regex, try this.

C#
private void TextBox_KeyPress(object sender, KeyPressEventArgs e)
        {           
            if (e.KeyChar == '\b')
                return;
            TextBox txtTemp = sender as TextBox;
            e.Handled = Regex.IsMatch(txtTemp.Text, @"^\-?[0-9]+(\.\d+)?$"); 
        }
 
Share this answer
 
v5
Comments
CHill60 30-Jan-15 11:25am    
I would suggest using decimal.TryParse() as the OP's expected results include decimals
Ramza360 30-Jan-15 11:27am    
Very True. Fixed. Thanks for pointing that out.
CHill60 30-Jan-15 11:41am    
No problem :)
I would actually use the Validating to check the value and use the KeyPress (or KeyUp) method to prevent invalid keys being added to the textbox.

This code will prevent anything that isn't "part of a number" being typed into the textbox (Note the inclusion of ,-comma. In some cultures this represents the decimal point)
C#
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
    textBox2.CausesValidation = true;
    if (new[] { '0','1', '2', '3',
            '4', '5', '6', '7', '8', '9', '+',
            '-','.', ',','\b' }.Contains(e.KeyChar))
        e.Handled = false;
    else
        e.Handled = true;
}

Then I would have something like this
C#
private void textBox2_Validating(object sender, CancelEventArgs e)
{
    const int maxDP = 2;
    var txt = ((TextBox)sender).Text.Trim();
    if (txt.Length == 0) return;
    decimal val;

    if (decimal.TryParse(txt, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign,
                              CultureInfo.CurrentCulture.NumberFormat, out val))
    {
        //OP does not want -0.00 although this is essentially equal to 0.00, so...
        if(val != 0 || txt[0] != '-')
            //Now check for decimal places - use your favourite method
            if (Math.Round(val * (decimal)(Math.Pow(10, maxDP)), 0)
                / ((decimal)(Math.Pow(10, maxDP))) == val)
                return;
    }

    MessageBox.Show(string.Format("Please enter a decimal value to maximum {0} decimal places", maxDP));
    e.Cancel = true;
    textBox2.CausesValidation = false;
}

Point of interest is the inclusion of
C#
textBox2.Focus();
textBox2.CausesValidation = false;
when validation fails. This allows the user to close the form if they decide not to bother entering a number.
It has have an associated
C#
private void textBox2_Leave(object sender, EventArgs e)
{
    textBox2.CausesValidation = true;
}}
to ensure that validation is switched back on along with the one in KeyPress. There are other (better) ways of achieving this documented by the way.
 
Share this answer
 
Comments
Ramza360 30-Jan-15 12:24pm    
Yea validating is another way to go. Prevent the key altogether.

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