Masking Textbox to accept only decimals

2019-03-05 10:46发布

I am using the technique from this link to mask my textbox to accept strings that are in decimal-format (Digits with a single period).

How to define TextBox input restrictions?

Here is the regex I put in the mask:

b:Masking.Mask="^\d+(\.\d{1,2})?$"

For some odd reason, it lets me input the digits but I cannot insert the period in my textbox.

I've also validated the regex here so regex is definitely correct.

http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx

What could be the issue?

2条回答
聊天终结者
2楼-- · 2019-03-05 11:15

Modify your regex with this:

^\d+([\.\d].{1,2})?$

DEMO

EDIT:

The above regex will also allow 123..1 that is more than 1 decimal point. so I just found the problem and fixed with the below one:

^(\d+)?+([\.]{1})?+([\d]{1,2})?$

DEMO

查看更多
再贱就再见
3楼-- · 2019-03-05 11:33

Either you can use the Regular Expression

^(\d+)?+([\.]{1})?+([\d]{1,2})?$

Or you can use below event

   bool blHasDot = false;
   private void txt_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b')
        {
            // Allow Digits and BackSpace char
        }
        else if (e.KeyChar == '.' && !blHasDot)
        {
            //Allows only one Dot Char
            blHasDot=true;
        }
        else
        {
            e.Handled = true;
        }
    }
查看更多
登录 后发表回答