0

I need to validate user input into a textbox to be a decimal number of precision exactly one? For example below are some of the cases..

  • if user inputs 1 then it's invalid

  • if user inputs 0 then its invalid

  • if user inputs 1.0 then its valid

  • if user inputs 1.1 then its valid

  • if user inputs 1.11 then its invalid

  • if user inputs 100.1 then its valid

How can I achieve this using C#(.net 3.5)?

Its a WPF textbox.

Thanks, -Mike

Mike
  • 3,204
  • 8
  • 47
  • 74

3 Answers3

2

Easiest way, to me, seems to be to use regular expressions. By interpreting the user input as a string, you can compare it with something like '[0-9]+\.[0-9]'

christopher
  • 26,815
  • 5
  • 55
  • 89
2

For a non-regex way of achieving this:

string input;
decimal deci;
if (input.Length >=3 && input[input.Length - 2].Equals('.') && Decimal.TryParse(input , out deci))
{
    // Success
}
else
{
    // Fail
}
Jamie Kelly
  • 309
  • 3
  • 15
0

Yes regular expression is the best way to check your condition:

For exactly NNNN.N (1234.5) use:

/^\d{4}\.\d$/

For optional .N (1234 1234. 1234.5) go with:

/^\d{4}(\.\d?)?$/

For numbers up to size of NNNN.N (1 .5 12.5 123. 1234 1234.5) go with:

/^(?=.*\d)\d{0,4}(\.\d?)?$/

And if you want to allow +/- at the beginning, then replace ^ with ^[-+]?.

Rohit Vyas
  • 1,949
  • 3
  • 19
  • 28