Reputation: 3294
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
Upvotes: 0
Views: 2699
Reputation: 309
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
}
Upvotes: 2
Reputation: 1969
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 ^[-+]?.
Upvotes: 0
Reputation: 27356
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]'
Upvotes: 2