使用Regex将文本框值验证为decimal / int [英] Validate textbox value into decimal/int using Regex

查看:84
本文介绍了使用Regex将文本框值验证为decimal / int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证小数点两位数字按键/文本更改事件中的文本框值,以便用户无法在文本框中输入无效值。

可接受的值。



-1

1

112.1

12345.00

-12434.00



无效价值

-0.00

1234.12354

1.231

1.000



我正在尝试跟随但无法得到正确的解决方案还有谷歌



 私有  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}))。?;
}





请帮忙。



谢谢

解决方案

如果您倾向于使用KeyPress事件,只需使用int.TryParse而不是Regex ..



这将允许每次按键检查更简单。不完全确定它是否比Regex.IsMatch更有效但更可读更可靠..



  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})?);
}





但是如果你需要使用正则表达式,试试这个。



 < span class =code-keyword> 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 +)

)?;
}


我实际上会使用验证来检查值并使用 KeyPress (或KeyUp)方法,以防止无效密钥被添加到文本框中。



此代码将阻止任何不是数字的一部分被输入到文本框中(注意包含,-comma。在某些文化中,这代表小数点)

  private   void  textBox2_KeyPress( object  sender,KeyPressEventArgs e) 
{
textBox2.CausesValidation = true ;
if new [] {' 0'' 1'' 2'' < span class =code-string> 3',
' 4'' 5'' < span class =code-string> 6',' 7'' 8'' 9'' +'
' - '' 。'' ,'' \ b'} .Contains(e.KeyChar))
e .Handled = false ;
else
e.Handled = true ;
}



然后我会有这样的事情

  private   void  textBox2_Validating( object  sender,CancelEventArgs e)
{
const int maxDP = 2 ;
var txt =((TextBox)sender).Text.Trim();
if (txt.Length == 0 返回;
decimal val;

if decimal .TryParse(txt,NumberStyles.AllowDecimalPoint | NumberStyles。 AllowLeadingSign,
CultureInfo.CurrentCulture.NumberFormat, out val))
{
/ / OP不需要-0.00虽然这基本上等于0.00,所以......
if (val!= 0 || txt [ 0 ]!= ' - '
// < span class =code-comment>现在检查小数位 - 使用您最喜欢的方法

if (Math.Round(val *( decimal )(Math.Pow( 10 ,maxDP)), 0
/(( decimal )(Math.Pow( 10 ,maxDP)))== val)
return ;
}

MessageBox.Show( string .Format( 请输入十进制值到最大{0}小数位,maxDP));
e.Cancel = true ;
textBox2.CausesValidation = false ;
}



兴趣点是包含

 textBox2.Focus();验证失败时
textBox2.CausesValidation = false ;

这允许用户在决定不打扰输入数字时关闭表单。

它有一个关联的

 私有  void  textBox2_Leave( object  sender,EventArgs e)
{
textBox2.CausesValidation = true ;
}}

确保验证与KeyPress中的验证一起重新开启。还有其他(更好的)方法可以实现这一目标。


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

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

解决方案

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

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.

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+)?


"); }


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)

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

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

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

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.


这篇关于使用Regex将文本框值验证为decimal / int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆