1

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?

Community
  • 1
  • 1
TtT23
  • 6,876
  • 34
  • 103
  • 174

2 Answers2

9

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

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
  • 1
    Oh wow it WAS the regex. I will mark this as an answer once 5 minutes pass. Thanks! – TtT23 Aug 31 '12 at 05:49
  • Hmm your edited answer gives me the following error: Error 11 parsing "^(\d+)?+([\.]{1})?+([\d]{1,2})?$" - Nested quantifier +. – TtT23 Aug 31 '12 at 06:33
  • In .Net it will change the meaning to `"match one or more of the preceding character"` Try to `Escape` special characters as `+` (inside an @"" literal).. so your regex will be `@"^(\d\+)?\+([\.]{1})?\+([\d]{1,2})?$"` – Vishal Suthar Aug 31 '12 at 06:47
  • With using that behavior, removing the +'s worked for me: `^(\d+)?([\.]{1})?([\d]{1,2})?$` – Ricky May 24 '17 at 10:09
1

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;
        }
    }
andy
  • 5,979
  • 2
  • 27
  • 49