Search code examples
c#.netwpfregexmaskedtextbox

Masking Textbox to accept only decimals


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?


Solution

  • 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