Pregunta

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?

¿Fue útil?

Solución

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

Otros consejos

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;
        }
    }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top